Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database: how do I sort GUID?

My primary key uses guid.

How do I sort GUID?

What about I create a datetime column and record a datetime stamp, I could then sort by datetime? is this the best way to do it? or are there better ways?

like image 993
001 Avatar asked Oct 19 '11 02:10

001


People also ask

Can GUID be sorted?

The really important thing is that ORDER BY GUID works, all bytes are evaluated and sorted, even if in a strange way.

How do I choose a GUID?

SQL Server NEWID to Generate GUID Type the below code in SSMS and execute. DECLARE @guid uniqueidentifier = NEWID(); SELECT @guid as 'GUID'; Here we created a variable named guid of data type uniqueidentifier.

What is the datatype for GUID?

The GUID data type is a 16 byte binary data type. This data type is used for the global identification of objects, programs, records, and so on. The important property of a GUID is that each value is globally unique. The value is generated by an algorithm, developed by Microsoft, which assures this uniqueness.

Can a GUID be a primary key?

GUIDs can be considered as global primary keys. Local primary keys are used to uniquely identify records within a table. On the other hand, GUIDs can be used to uniquely identify records across tables, databases, and servers.


2 Answers

SELECT * 
FROM myTable
ORDER BY CAST(myGuid AS VARCHAR(36))
like image 135
Mark Avatar answered Oct 25 '22 17:10

Mark


A Guid is just what the name implies, a unique identifier. Identity doesn't imply order, it just gives you a way to determine whether 2 things are supposed to be identical. In order to sort, you need to determine what it means to be greater or maller than something else. From your question, it seems that sorting should be based on creation time; Guids won't help you with that.

like image 1
Mathias Avatar answered Oct 25 '22 15:10

Mathias