I want to create a varchar column in SQL that should contain N'guid'
while guid
is a generated GUID by .NET (Guid.NewGuid) - class System.Guid.
What is the length of the varchar
I should expect from a GUID?
Is it a static length?
Should I use nvarchar
(will GUID ever use Unicode characters)?
varchar(Guid.Length)
PS. I don't want to use a SQL row guid data-type. I am just asking what is Guid.MaxLength
.
36, and the GUID will only use 0-9A-F (hexidecimal!).
12345678-1234-1234-1234-123456789012
That's 36 characters in any GUID--they are of constant length. You can read a bit more about the intricacies of GUIDs here.
You will need two more in length if you want to store the braces.
Note: 36 is the string length with the dashes in between. They are actually 16-byte numbers.
22 bytes, if you do it like this:
GUIDs are 128bits, or
So yes, min 20 characters long, which is actually wasting more than 4.25 bits, so you can be just as efficient using smaller bases than 95 as well; base 85 being the smallest possible one that still fits into 20 chars:
:-)
I believe GUIDs are constrained to 16-byte lengths (or 32 bytes for an ASCII hex equivalent).
It depends on how you format the Guid:
Guid.NewGuid().ToString()
=> 36 characters (Hyphenated)outputs:
12345678-1234-1234-1234-123456789abc
Guid.NewGuid().ToString("D")
=> 36 characters (Hyphenated, same asToString()
)outputs:
12345678-1234-1234-1234-123456789abc
Guid.NewGuid().ToString("N")
=> 32 characters (Digits only)outputs:
12345678123412341234123456789abc
Guid.NewGuid().ToString("B")
=> 38 characters (Braces)outputs:
{12345678-1234-1234-1234-123456789abc}
Guid.NewGuid().ToString("P")
=> 38 characters (Parentheses)outputs:
(12345678-1234-1234-1234-123456789abc)
Guid.NewGuid().ToString("X")
=> 68 characters (Hexadecimal)outputs:
{0x12345678,0x1234,0x1234,{0x12,0x34,0x12,0x34,0x56,0x78,0x9a,0xbc}}
The correct thing to do here is to store it as
uniqueidentifier
- this is then fully indexable, etc. at the database. The next-best option would be abinary(16)
column: standard GUIDs are exactly 16 bytes in length.If you must store it as a string, the length really comes down to how you choose to encode it. As hex (AKA base-16 encoding) without hyphens it would be 32 characters (two hex digits per byte), so
char(32)
.However, you might want to store the hyphens. If you are short on space, but your database doesn't support blobs / guids natively, you could use Base64 encoding and remove the
==
padding suffix; that gives you 22 characters, sochar(22)
. There is no need to use Unicode, and no need for variable-length - sonvarchar(max)
would be a bad choice, for example.