Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQL server how do I order table rows by insertion order if primary key is GUID?

I've started using GUIDs over auto-increment integers for my primary keys.

However, during development I'm used to querying (from SQL management studio or visual studio) database in order to see what records my application just inserted, and I'm pissed off by the fact that I cannot order by primary key desc in order to see the most recent records.

Is there a way to accomplish tihs?

like image 206
tishma Avatar asked Dec 28 '22 01:12

tishma


1 Answers

You can't order a GUID column based on insertion order. You'll need to rely on another column.

My suggestion is to add a column called CreationMoment as a DateTime with a default value of GETDATE(). Theoretically you could have collisions (i.e. identical date / time of creation), so you'll have to decide if that data type is appropriate. In my experience it's never been an issue.

like image 74
Yuck Avatar answered Jan 31 '23 06:01

Yuck