Today I just discover, at least what I see, as A major flaw in the way SQL Server Operates. I was under the impression that SQL Implicitly Orders by FIFO when Executing Queries with out explicit ORDER BY Clauses. Naturally in most cases this resolves to order by ID (because generally ID's are Given Sequentially). However Today I discovered this is not true when I executed this code
var BadQuery = Model.Titles.Where(t => t.ID > 19632)
.Select(i => new { i.ID, i.ExtTitleID })
.Take(10).ToList();
//BadQuery Results
//ID: 121148 ExtTitleID: 0001234
//ID: 132638 ExtTitleID: 000263
//ID: 132639 ExtTitleID: 000360
//ID: 132640 ExtTitleID: 000379
//ID: 132641 ExtTitleID: 000387
//ID: 132642 ExtTitleID: 000409
//ID: 132643 ExtTitleID: 000417
//ID: 134246 ExtTitleID: 000514
//ID: 132644 ExtTitleID: 000522
//ID: 132645 ExtTitleID: 000530
var GoodQuery = Model.Titles.Where(t => t.ID > 19632)
.Take(10).ToList()
.Select(i => new { i.ID, i.ExtTitleID }).ToList();
//GoodQuery Results
//ID: 19633 ExtTitleID: 30706
//ID: 19634 ExtTitleID: 30708
//ID: 19635 ExtTitleID: 30709
//ID: 19636 ExtTitleID: 3071
//ID: 19637 ExtTitleID: 30710
//ID: 19638 ExtTitleID: 30711
//ID: 19639 ExtTitleID: 30712
//ID: 19640 ExtTitleID: 30714
//ID: 19641 ExtTitleID: 30719
//ID: 19642 ExtTitleID: 3072
The Bad Query Is being ordered by the ExtTitleID, which is a varchar in the database. This is not what I expected. While The Good Query Orders Sequentially by ID or FIFO.
It seems to only order by ExtTitleID if I add a select statement in the Query before. The Good Query ToList before it's select meaning the select is occuring in Linq to Object (c#) instead of LinqToEntities(SQL)
My question is what are the specifications for how SQL determines order? Also, Does this anomaly mean I have to refactor and explicitly order anything that has a select statement in the Query?