whadiz.com: What is?
Search Articles:     Home | About | Tools | Contact Us
You are here: Home > Databases > Sql Server > newid
Board Games
Online Games
Sql Server
Visual C# in ASP.Net
Web Design

Clever Facts Section

What is Sql newid? | Sort using Sql newid | Unique newid | Is newid unique? | Sql newid | Globally unique identifier

What is newid?

Sql newid() is a Transact-Sql function for returning a “uniqueidentifier”, commonly known as globally unique identifier. Sql newid() can be used to randomly sort records. 

What type of results can I expect from newid?

Try running sql newid() as follows:

print newid();

Sql newid() will return a result that resembles the following:


With each run of the statement "print newid();" a different globally unique identifier will be obtained.

Using newid to randomly sort records?

Try the following example code:

FROM myTable
ORDER BY newid();

Because sql newid() returns a globally unique identifier, the resultset would be randomly sorted. This approach can be considered better than running a cursor over a temp table.

Using this approach, a single random row can be selected as follow:

FROM myTable
ORDER BY newid();

Is newid unique?

Yes, newid() is unique. newid() returns a globally unique identifier. newid() will be unique for each call of newid().

Thus, newid() can be used as the value of a primary key of a sql server table. Values returned by newid() can be inserted into a primary key column of type "uniqueidentifier". Here is an example of a "uniqueidentifier" primary key column, with newid() used as the default value:

CREATE TABLE [tblUsers] (
    [UserId] [uniqueidentifier] NOT NULL DEFAULT (newid()),
    [UserName] [varchar](256) NOT NULL,
    PRIMARY KEY ([UserId])

Where have you tested newid?

newid() was successfully tested under Sql Server 2005 and Sql Server 2000.

Link to this article:

Browse some more: Next Article | Next Fact | More Sql Server Articles | More Clever Facts

Copyright © 2024 whadiz.com. All rights reserved.
whadiz.com: What is newid? | Unique newid | Sort using newid | Is newid unique? | Sql newid | Globally unique identifier
Home of the answer "what is"