Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am trying to understand the practical real-life usage of
NewId
and '
NewSequentialId
, I usually use the
Identity
property when creating new table like this:
CREATE TABLE MYTABLE
[ID] INT PRIMARY KEY IDENTITY,
[NAME] NVARCHAR(MAX) NOT NULL
Is the above code not the best practice, If so should I replace it with this:
CREATE TABLE MYTABLE
[ID] UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWID(),
[NAME] VARCHAR(MAX) NOT NULL
Or with this:
CREATE TABLE MYTABLE
[ID] UNIQUEIDENTIFIER ROWGUIDCOL PRIMARY KEY DEFAULT NEWSEQUENTIALID(),
[NAME] nVARCHAR(MAX) NOT NULL
Question: Is NewId or NEWSEQUENTIALID a replacement for Identity, if not when to use each one?
I am not trying to use the NewId
or NewSequentialId
as Primary Key
, the code above is for demonstration purpose only, and maybe this code is better like this:
CREATE TABLE MYTABLE
[ID] INT NOT NULL PRIMARY KEY,
[ROWGUID] UNIQUEIDENTIFIER ROWGUIDCOL DEFAULT NEWSEQUENTIALID(),
[NAME] nVARCHAR(MAX) NOT NULL
–
–
–
If I understood it right than a GUID is not always good in performance because it is not an sortable field for an index.
The sequentialid can overcome this problem by creating GUID's that are much better sortable and thus makes better index for your table.
I know it is a bit more complicated than this but I am trying to explain as simple as possible.
So if you want to use GUID as primary keys than I suggest using the sequentialID.
You should ask yourself why you want a GUID as primary key, if not needed than dont.
–
The primary use of GUIDs as primary keys is in distributed systems, where you want unique IDs among clients without the overhead of a roundtrip to the server/database.
They can come with their own problems, such as fragmentation if used as a clustering key (which can be mitigated with appropriate periodic index rebuilds).
I would not use SEQUENTIALID
; instead use a 'Comb' GUID if you want ordering.
The Cost of GUIDs as Primary Keys
–
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.