Tip of the Day : Example Uses of the NEWID Function

Welcome to SQL Server Helper !!!

This site is intended for those who are beginning to use SQL Server as part of their day-to-day activities.  You will find in this site a collection of useful functions, triggers, stored procedures and tips and tricks related to SQL Server.

Should you have any comments or questions regarding this site or if you want to ask SQL Server-related questions, e-mail us here.

We hope we are able to help and we are glad to help!!!

SQL Server Tip of the Day - May 31, 2025

Example Uses of the NEWID Function

 

The NEWID() function in SQL Server creates a unique value of type uniqueidentifier.  One use of the NEWID() function is in generating random rows from a table.

SELECT TOP 20 [LottoNumber]
FROM [dbo].[LottoParticipants]
ORDER BY NEWID()

Another use of the NEWID() function is in generating random numbers.  The uniqueidentifier generated by the NEWID() can be converted to VARBINARY which in turn can be converted to an integer number.  The random number generated will include negative numbers.  If only positive numbers are desired, simply get the absolute number of the result:

SELECT ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) AS [RandomNumber]

If there’s a maximum number required for the random number generated, simply use the MODULO operator to limit the numbers generated.  The following query generates a random number between 1 and 100:

SELECT ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) % 100 + 1 AS [RandomNumber]

SQL Server 2012

SQL Server 2008

User-Defined Functions

Date Functions

A collection of useful user-defined functions that deal with dates.

String Functions

A collection of useful user-defined functions that deal with strings (varchar/char/nvarchar/nchar).

Tree Functions

A collection of useful user-defined functions that deal with tree or hierarchical design structures.

Table-Valued Functions

A collection of useful table-valued user-defined functions that can be used to join with other tables.

SQL Server Built-in Functions

A reference to all built-in functions available within SQL Server grouped into categories.

Tips and Tricks

A collection of useful SQL Server-related tips and tricks:

SQL Server Error Messages

A list of SQL Server error messages and for certain error messages, discusses ways on how to solve the error or work around them:

Frequently Asked Questions