Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Why Two Identical LINQ Queries Return Rows in a Different Order Each Time

- 05.09.26 - ErcanOPAK

🔧 Same Query, Same Data – a Different Row Order Every Time You Run It

A LINQ query against Entity Framework returns the exact same set of rows on every run, just shuffled into a different order each time – no ORDER BY was written on purpose, but the assumption was that the database would at least be CONSISTENT about the order it left rows in.

🐞 The Problem

var orders = await db.Orders
    .Where(o => o.CustomerId == customerId)
    .ToListAsync();

// Run 1: returns rows in order [102, 105, 101, 103]
// Run 2, same data, same query: [105, 101, 103, 102]
// - a UI list built on this "just moves around" for no
//   apparent reason between page loads.

🔍 Why This Happens

SQL, and by extension Entity Framework, makes NO GUARANTEE about
row order unless an explicit ORDER BY is specified - the relational
model is fundamentally a set of rows, not a sequence. Without an
ORDER BY, the database is free to return rows in whatever order is
most convenient internally - influenced by index usage, physical
storage layout, parallel execution plans, or even just which CPU
core happened to scan which data page first. It can appear stable
for a long time purely by coincidence, then change the moment an
index changes or the query plan is recompiled.

✅ The Fix: Always Add an Explicit OrderBy for Anything User-Visible

  • Add .OrderBy(o => o.Id) (or whatever column defines the order you actually want) to every query whose result order matters to a human or to downstream logic – never rely on implicit database ordering, even if it ‘seems to always work.’
  • For paginated results specifically, an explicit, stable ORDER BY isn’t just cosmetic – without one, using .Skip()/.Take() across separate requests can return duplicate OR missing rows if the underlying implicit order shifts between calls.
  • If a specific column doesn’t guarantee a unique order (ties on the same value), add a secondary tiebreaker column (like Id) to the OrderBy so the order is fully deterministic, not just ‘usually deterministic.’

📦 Correct Version

var orders = await db.Orders
    .Where(o => o.CustomerId == customerId)
    .OrderBy(o => o.CreatedDate)
    .ThenBy(o => o.Id) // tiebreaker for a fully deterministic order
    .ToListAsync();

A database was never promising to remember the order you’re used to seeing — without an explicit ORDER BY, ‘the order it usually comes back in’ was always just a coincidence waiting to change.

— C# Best Practice

Related posts:

ASP.NET Core “Response Compression Not Working” — The Missing MIME Types

C#: Use Tuple Deconstruction in foreach for Dictionary Iteration

C#: Use Encapsulation to Protect Data

Post Views: 5

Post navigation

CSS: Fix an Image That Won’t Center No Matter What Margin or Text-Align You Try
C#: Fix a Switch Expression That Silently Matches the Wrong Case Because of Pattern Order

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

October 2026
M T W T F S S
 1234
567891011
12131415161718
19202122232425
262728293031  
« Sep    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (952)
  • How to add default value for Entity Framework migrations for DateTime and Bool (939)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (837)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (624)
  • Add Constraint to SQL Table to ensure email contains @ (590)
  • Average of all values in a column that are not zero in SQL (553)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (526)
  • Find numbers with more than two decimal places in SQL (468)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps
  • Photoshop: Fix a Color Profile Mismatch That Makes Printed Output Look Nothing Like What You Saw On Screen
  • WordPress: Fix Search Results That Return Pages From a Theme You Deactivated Months Ago
  • Visual Studio: Fix a Test Project That Builds Fine Alone but Fails to Discover Any Tests After a NuGet Restore
  • ASP.NET Core: Fix a File Upload That Times Out on Slow Connections Only Because Kestrel’s Minimum Data Rate Feature Kicked In
  • JavaScript: Fix an Array Destructuring Default Value That Silently Never Applies Because null Was Passed Instead of Undefined

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (952)
  • How to add default value for Entity Framework migrations for DateTime and Bool (939)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (837)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com