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

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:

F68794B1-E2AB-4453-AB40-EABE68D879C2

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:

SELECT *
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:

SELECT TOP 1 id
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 © 2021 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"