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. |