I've always figures SQL Server was intelligent, but today it called me a liar. :P
I don't often sort on UNIQUEIDENTIFIER columns but for a master table data load script I decided to keep the data consistent so I could see changes in source control easily. But alas the results were not quite as I had expected. Take the following snippet as an example:
CREATE TABLE [dbo].[Foo] (
[Id] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY CLUSTERED
) ON [PRIMARY];
GO
INSERT INTO [dbo].[Foo] VALUES ('00000000-0000-FFFF-0000-000000000000');
INSERT INTO [dbo].[Foo] VALUES ('FFFFFFFF-0000-0000-0000-000000000000');
INSERT INTO [dbo].[Foo] VALUES ('00000000-0000-0000-0000-FFFFFFFFFFFF');
INSERT INTO [dbo].[Foo] VALUES ('00000000-FFFF-0000-0000-000000000000');
INSERT INTO [dbo].[Foo] VALUES ('00000000-0000-0000-0000-000000000000');
INSERT INTO [dbo].[Foo] VALUES ('00000000-0000-0000-FFFF-000000000000');
GO
SELECT * FROM [dbo].[Foo] ORDER BY [Id] ASC;
SELECT * FROM [dbo].[Foo] ORDER BY CONVERT(VARCHAR(36), [Id]) ASC;
GO
DROP TABLE [dbo].[Foo];
GO
Now what I expected to happen in the first select line is for the data to come back ordered like it is in the second select line. However I notice it is in fact ordered a little differently.
Here is what an order by on the Id column results in:
00000000-0000-0000-0000-000000000000
FFFFFFFF-0000-0000-0000-000000000000
00000000-FFFF-0000-0000-000000000000
00000000-0000-FFFF-0000-000000000000
00000000-0000-0000-FFFF-000000000000
00000000-0000-0000-0000-FFFFFFFFFFFF
Here is what an order by the string representation of the Id column results in:
00000000-0000-0000-0000-000000000000
00000000-0000-0000-0000-FFFFFFFFFFFF
00000000-0000-0000-FFFF-000000000000
00000000-0000-FFFF-0000-000000000000
00000000-FFFF-0000-0000-000000000000
FFFFFFFF-0000-0000-0000-000000000000
Now I wonder why... Anyone know. I am too lazy too look in BOL (aka Google). :P

Microsoft Xbox MVP |
http://craign.net/