// conversion reference

SQL NEWID function

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

카테고리
Conversion
Returns
uniqueidentifier
In this category
33 of 39

구문

NEWID()

엔진 지원

엔진Support메모
SQL Server 예 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

예시

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();

알아 두면 좋은 정보

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