// conversion reference

SQL NEWID function

SELECT NEWID() returns a random version 4 uniqueidentifier. It is also behind the ORDER BY NEWID() random-sample idiom.

Catégorie
Conversion
Returns
uniqueidentifier
In this category
33 of 39

Syntaxe

NEWID()

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Oui Supported under this name.
PostgreSQL Different name or syntax gen_random_uuid() is the twin
MySQL Different name or syntax UUID() is the twin, but v1
SQLite Different name or syntax no built-in; hex(randomblob(16))
Oracle Different name or syntax SYS_GUID() returns raw bytes

Exemples

SQL Server

SELECT NEWID() AS guid;

SQL Server

CREATE TABLE sessions (
  id uniqueidentifier PRIMARY KEY DEFAULT NEWID(),
  token nvarchar(200)
);

SQL Server

SELECT TOP 5 name FROM users ORDER BY NEWID();

Bon à savoir

  • Random GUIDs fragment clustered indexes: NEWSEQUENTIALID() (allowed only in DEFAULT constraints) grows more monotonically for hot-insert tables.
  • ORDER BY NEWID() is the classic random sample, but it scans and sorts every row; TABLESAMPLE samples pages faster and coarser.
  • uniqueidentifier sorts by its last six bytes first, not left to right, so ORDER BY on a GUID column does not match the order of the text form. This is why NEWSEQUENTIALID output looks unordered as text.

Questions about NEWID

How do I sample random rows?

ORDER BY NEWID() with TOP is simple and slow on big tables: it sorts everything. TABLESAMPLE picks pages instead; or pre-generate a random column and index it.

NEWID or NEWSEQUENTIALID?

NEWID for values handed out anywhere; NEWSEQUENTIALID for clustered-index DEFAULTs: sequential GUIDs land closer together and fragment less.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.