views:

102

answers:

2

Hi, This question is just for a sake of knowledge. I don't have any practical implementation of this.

I have fired a query like

SELECT RAND() RANDOMCOLUMNS,COL1

FROM tblY 

ORDER BY RANDOMCOLUMNS

Output:

RANDOMCOLUMNS        COL1
================================
0.567773034904758   1

0.567773034904758   2

0.567773034904758   3

0.567773034904758   4

When I fire the same query with NEWID(), I got the following output

RANDOMCOLUMNS                           COL1
===========================================
B953F9A9-BE22-4651-8669-5CC6A5269911    4

50293D75-4139-4A75-883F-81DAA91ED4E6    1

0A9B1D56-68FD-4060-AA6B-89791DAF8924    3

4C3A2765-4EA2-493B-8AA9-EBA414D7AAC2    2

As you can see that, COL1's values order has changed.

Question is why and how it happened?

As far asI know, NEWID() generates unique GUID. Does it have to do anything with Column ordering?

Thanks in advance

+3  A: 

In the first example, you were sorting by RANDOMCOLUMNS. But because the same value was in each row, the order was not modified. In the second example, you're sorting by a column that has different values for each row. Sorting by GUID is strange in SQL Server, but it is still sorting by that column nonetheless, since it's in your ORDER BY clause.

Jacob
How is it sorting the guids anyway? The only sense I can make out of the example is "sort by last block" (which is just a guess considering the sample size of 4).
balpha
The link I provided (http://sqlblog.com/blogs/alberto_ferrari/archive/2007/08/31/how-are-guids-sorted-by-sql-server.aspx) explains much better than I can, but based on the sorting I just did on a larger table of my own, that looks about right.
Jacob
Sorry, I had missed the link. Interesting read.
balpha
+2  A: 
  • In query 1 you are sorting on the constant (per SELECT) RAND() value
  • In query 2 you are sorting on a dynamic (per row) NEWID() value

In both queries, Col1 output order is irrelevant because you have not mentioned it. It is simply sheer coincidence that you get Col1 out in order in query 1 because of how the optimiser decided to read the data from the table.

There is no guaranteed output order unless an ORDER BY clause is used. You have not specified any sort on Col1, so this is standard behaviour.

gbn