The quickest way to generate a random number in T-SQL is to use the RAND() function for a decimal between 0 and 1, or combine it with arithmetic for integers. For a random integer between 1 and 100, use CAST(RAND() * 100 AS INT) + 1. However, RAND() behaves differently in a set-based query than you might expect, so for per-row randomness you often need NEWID() or CHECKSUM(NEWID()).
Background: Why Random Numbers Are Tricky in SQL
Random number generation in T-SQL is not as straightforward as in procedural languages. The core issue is that SQL is set-based: a query processes many rows at once, and functions like RAND() are evaluated only once per statement unless you force re-evaluation. This leads to the common pitfall where every row in a result set gets the same random value. Understanding this behavior is key to writing correct code.
Another layer is that SQL Server uses a pseudo-random algorithm, not true randomness. RAND() with a seed produces a repeatable sequence, which is useful for testing but not for cryptography. For security-sensitive randomness (like session tokens), you must use CRYPT_GEN_RANDOM() instead.
How RAND() Works and Its Limitations
RAND([seed]) returns a float from 0 (inclusive) to 1 (exclusive). If you supply a seed, the sequence is deterministic: the same seed always produces the same first number. Without a seed, SQL Server uses a time-based seed, so consecutive calls differ.
In a SELECT statement, RAND() is evaluated once per row only if you include a column reference or use a correlated subquery. For example, this query gives the same value on every row:
SELECT TOP 5 RAND() AS RandomValue FROM sys.objects;
To get a different value per row, you can use NEWID() as a seed, but that is inefficient. A better approach is to use CHECKSUM(NEWID()) and then normalize.
Generating Random Integers and Decimals
To get a random integer between @min and @max (inclusive), use this formula:
DECLARE @min INT = 1, @max INT = 100;
SELECT CAST((RAND() * (@max - @min + 1)) + @min AS INT);
This works because RAND() returns a value in [0,1). Multiplying by the range size gives [0, range), adding the minimum shifts it, and casting to INT truncates the decimal. For a decimal with a specific number of decimal places, multiply and round instead:
SELECT ROUND(RAND() * 10, 2); -- random decimal between 0 and 10
For per-row random integers in a result set, use ABS(CHECKSUM(NEWID())) % (@max - @min + 1) + @min. The modulo operator gives a value in [0, range), and adding the minimum shifts it.
Using NEWID() for Row-Level Randomness
When you need a different random number for each row in a SELECT, NEWID() is the standard solution. NEWID() generates a unique identifier (GUID) for each row. You can convert it to a number using CHECKSUM(), which returns an integer from the GUID.
Example: random integer per row between 1 and 10:
SELECT ABS(CHECKSUM(NEWID())) % 10 + 1 AS RandomInt
FROM sys.objects;
Note: CHECKSUM() can return negative values, so use ABS() to ensure a positive result. Also, the distribution is not perfectly uniform because the modulo operation on a large integer range can introduce slight bias, but for most non-critical applications it is acceptable.
For random ordering (like picking a random row), use ORDER BY NEWID():
SELECT TOP 1 * FROM Employees ORDER BY NEWID();
This is simple but can be slow on large tables because it assigns a GUID to every row and sorts them. For large tables, consider using TABLESAMPLE or a random primary key approach.
Cryptographic Random Numbers with CRYPT_GEN_RANDOM()
For passwords, tokens, or any security-sensitive data, use CRYPT_GEN_RANDOM(). This function generates a cryptographic random number of a specified length in bytes. It returns a varbinary value.
SELECT CRYPT_GEN_RANDOM(4); -- 4 random bytes
To convert to an integer, you can use CONVERT(INT, CRYPT_GEN_RANDOM(4)), but be careful with sign. A common pattern for a random positive integer within a range is:
DECLARE @max INT = 1000;
SELECT ABS(CONVERT(INT, CRYPT_GEN_RANDOM(4))) % @max;
This is slower than RAND() but provides strong randomness. Use it only where security matters, not for general purpose.
Common Pitfalls and How to Avoid Them
- Same value on every row: As mentioned,
RAND()without a per-row seed gives the same value. UseNEWID()or a column reference. - Negative numbers:
CHECKSUM(NEWID())can be negative; always wrap withABS(). - Off-by-one errors: The formula
CAST(RAND() * @max AS INT)gives values from 0 to @max-1. To include @max, add 1 after casting. - Performance on large tables:
ORDER BY NEWID()is O(n log n) and can be slow. For large tables, consider usingTABLESAMPLEor a random key lookup. - Non-uniform distribution: Modulo bias is real but usually negligible for small ranges. For critical statistical work, use a rejection sampling method.
Alternatives: TABLESAMPLE and Random Row Selection
If you need to select a random row from a large table, ORDER BY NEWID() is often too slow. SQL Server offers TABLESAMPLE, which returns a random sample of rows based on a percentage or number of rows. However, TABLESAMPLE does not guarantee an exact number of rows and can be inconsistent with small tables.
SELECT * FROM Employees TABLESAMPLE (10 PERCENT);
For a single random row, a better approach is to generate a random ID and look it up, assuming you have a numeric primary key with no gaps:
DECLARE @randomId INT = (SELECT TOP 1 EmployeeID FROM Employees ORDER BY NEWID());
SELECT * FROM Employees WHERE EmployeeID = @randomId;
But this still uses NEWID() on the whole table. A more efficient method is to use a random number between the min and max ID and then find the next available ID, but that gets complex. For most cases, ORDER BY NEWID() is fine for tables up to a few hundred thousand rows.
Frequently Asked Questions
How do I get a random date in T-SQL?
Generate a random number of days between a start and end date. For example, to get a random date in 2023: SELECT DATEADD(DAY, CAST(RAND() * 365 AS INT), '2023-01-01'). Adjust the range as needed.
Why does RAND() return the same value in a loop?
If you call RAND() multiple times in the same batch without a seed, it returns a new value each time. But if you use a seed, it returns the same first value. In a loop, if you don’t re-seed, you get different values because the seed is updated internally. If you see the same value repeatedly, you might be using a constant seed or the loop is reinitializing.
Can I use RAND() for a random primary key?
Yes, but be careful about collisions. If you need a unique random number, use NEWID() as a GUID or combine RAND() with a sequence. For a large table, random keys can cause page splits and performance issues; consider using an identity column instead.
What is the difference between RAND() and CRYPT_GEN_RANDOM()?
RAND() is a pseudo-random number generator that is fast but predictable if seeded. CRYPT_GEN_RANDOM() uses the operating system’s cryptographic random number generator, which is slower but unpredictable and suitable for security. Use CRYPT_GEN_RANDOM() for passwords, tokens, or any data that must not be guessed.
How do I generate a random string in T-SQL?
You can combine random numbers with character sets. For example, to generate a random 8-character string from A-Z and 0-9: use CHAR(65 + ABS(CHECKSUM(NEWID())) % 26) for letters, and concatenate with digits. A common pattern is to use NEWID() and take a substring: LEFT(REPLACE(NEWID(), '-', ''), 8) gives a random hex string.
Related
- Switch Desktop Shortcut: How to Create & Use It
- Generate Random Number NumPy: How to Use np.random
- Data Entry Computer Skills: A Practical Guide
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Group Rows Count: How to Count Rows in GroupsExcel’s Group command does not calculate a row count; it only lets you collapse or expand selected rows.…
- Where Is the Flash Fill Button in Excel? Find It FastIn Excel for Microsoft 365 on Windows, Flash Fill is on the Data tab, in the Data Tools…
- How to Freeze a Group of Cells in Excel with Freeze PanesTo keep a group of rows and columns visible while you scroll in Excel, select the cell immediately…
- Google Debt Snowball Spreadsheet: Build One in SheetsYes. You can build a debt snowball spreadsheet in Google Sheets by listing each debt, sorting debts from…
- Remove Duplicates Based on Two Columns in Excel: StepsTo remove duplicates based on two columns in Excel, select the entire data range, choose Data > Remove…
- Excel Lock Slicer in Place? Position and Protect ItYes. In Excel for Microsoft 365 on Windows, select the slicer, open Size and Properties, and under Properties…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.