views:

49

answers:

2

I'm wondering how SQL Server orders data that is returned from a query and the Id columns of the respective tables are all of type uniqueidentifier.

I'm using NHibernate GuidComb when creating all of the GUIDs and do things like:

Sheet sheet = sheetRepository.Get(_SheetGuid_); // has many lines items
IList<SheetLineItem> lineItems = sheet.LineItems;

I'm just trying to figure out how they'll be ordered when I do something like:

foreach (SheetLineItem lineItem in lineItems)

I can't see to find a good article on the way GUIDs are compared by SQL when being ordered, if that's what's happening.

+6  A: 

GUIDs are sorted this way by the ORDER BY. Quoting the article...

  • 0..3 are evaluated in left to right order and are the less important, then
  • 4..5 are evaluated in left to right order, then
  • 6..7 are evaluated in left to right order, then
  • 8..9 are evaluated in right to left order, then
  • A..F are evaluated in right to left order and are the most important
gbn
@gbn I had found that article. Does it suggest that '00000000-0000-0000-0000-010000000000' is the largest GUID in that list and '01000000-0000-0000-0000-000000000000' is the smallest? In that respect, for the following A..F series: 9d6500c1d13c, 9d6500c5c1da, 9d6500c60f1e, are they ordered correctly for ASC because block D is c1, c5, c6 respectively?
Chris F
Chris F: I haven't studied the article in depth because I don't use GUIDs with any kind of order... sorry.
gbn
+4  A: 

Unless you incude an ORDER BY clause SQL Server doesn't guarantee any order on the results. It may sem to come back in the some order consistently (e.g. clustered index order) but you can't be sure this will always be the case (e.g. if the query is split and executed on multiple threads, when the results are combined, the order may be different on each execution since the threads may complete in different orders).

The only way to get a particular order is to use an ORDER BY clause. In NHibernate, this would be achieved by speifying an order-by="..." on your bags (or equivalent) in your mapping files.

See the NHibernate docs for more info on "order-by": http://nhforge.org/doc/nh/en/index.html

Daniel Renshaw
+1 I had totally forgotten that I can set order-by for each particular bag. Thanks for the reminder.
Chris F