I have a SQL Server table that is using a uniqueidentifier as a clustered primary key. After creating the table and inserting several rows, I rebooted my server. The column uses NEWSEQUENTIALID() as its default value.
After reboot however, the next insert created a row with a GUID that was lower in value than those before, causing it to appear at the top of a SELECT * statement.
My question: is there any way to prevent shuffling (AKA preserve the ordering of rows) while using a GUID type clustered primary key?
If you want to guarantee chronological order, add a column called
CreatedDate, set it to not allow NULLs, and set the default toCURRENT_TIMESTAMP. Then to get the last 10 rows, you can say:This way your
TOPmakes sense. WithoutORDER BY, as marc explained, yourTOPis meaningless and while the results will be relatively predictable (they’re not quite random, I’d prefer the term “arbitrary”), they are not going to have any reliability to be ordered in the same order they were inserted. This is true whether you use a GUID or an integer for your primary key – no guarantees.You are never going to be able to guarantee order preservation with
NEWSEQUENTIALID(), sorry, that’s just not how it works.