You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Queryable.OrderBy在SQL Server数据库中是否属于不稳定排序?

Is Queryable.OrderBy Unstable in SQL Server?

Yes, you’re absolutely right—Queryable.OrderBy is unstable when working with SQL Server, and here’s a breakdown of why this happens and how to address it:

  • Unlike LINQ to Objects' OrderBy (which is explicitly stable, preserving the original order of elements with equal sort keys), Queryable.OrderBy translates directly to SQL’s ORDER BY clause. SQL Server’s ORDER BY does not guarantee stable sorting when there are duplicate values in the sort column(s).
  • When your timestamp values are identical, SQL Server doesn’t retain the original order of those rows. Instead, it returns them in an order determined by internal factors like index structure, storage layout, or query execution plan optimizations—this can vary between runs, leading to the inconsistent results you’re seeing.
  • The reason MSDN doesn’t explicitly state this is because Queryable.OrderBy's behavior depends entirely on the underlying LINQ provider. For SQL Server, it inherits the instability of the database’s own sorting logic.

Fix for Consistent Results

If you need stable, predictable sorting even when timestamps are identical, add a secondary sort key that uniquely identifies each row (like a primary key ID):

yourQuery.OrderBy(x => x.Timestamp).ThenBy(x => x.Id);

This ensures that rows with the same timestamp will always be ordered by their unique ID, eliminating the inconsistency.

内容的提问来源于stack exchange,提问作者Igor Yalovoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:06:54