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.OrderBytranslates directly to SQL’sORDER BYclause. SQL Server’sORDER BYdoes 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
相关产品推荐
相关产品推荐

