The fastest way to generate a random number in Microsoft SQL Server is to use the RAND() function, which returns a float value from 0 (inclusive) to 1 (exclusive). For a random integer within a range, combine RAND() with arithmetic: FLOOR(RAND() * (max - min + 1)) + min. However, because RAND() is evaluated once per row in a query, you often need NEWID() or a seed to get truly different random values per row. This article explains both approaches, their pitfalls, and how to choose the right one for your use case.
How RAND() Works in SQL Server
RAND() is a built-in SQL Server function that returns a pseudo-random float between 0 and 1. It is deterministic when given a seed: RAND(seed) always returns the same value for the same seed. Without a seed, SQL Server uses a system-generated seed based on the connection and time, so consecutive calls in the same session return different values.
Example: SELECT RAND(); might return 0.713724, while SELECT RAND(42); always returns 0.654… for that seed. This determinism is useful for reproducible tests but not for random distribution across rows.
Key limitation: In a single SELECT statement, RAND() is evaluated only once per row? Actually, it is evaluated once per row, but the value is the same for all rows in the same statement because the seed is fixed for the statement. So SELECT RAND() FROM sys.objects; returns the same number for every row. To get a different random number per row, you need a per-row seed or use NEWID().
Generating a Random Integer in a Range
To get a random integer between @min and @max (inclusive), use the formula:
FLOOR(RAND() * (@max - @min + 1)) + @min
For example, to get a random number between 1 and 10:
SELECT FLOOR(RAND() * 10) + 1;
This works because RAND() returns a value in [0,1). Multiplying by 10 gives [0,10), FLOOR gives integers 0-9, then adding 1 gives 1-10. If you need a decimal random number, just use RAND() directly or multiply by a range and add an offset.
For a random decimal between 5 and 15: SELECT RAND() * 10 + 5; returns values from 5.0 to 14.999…
Per-Row Random Values with NEWID()
When you need a different random number for each row in a result set, use NEWID() to generate a unique identifier and convert it to a numeric value. The common method is to use CHECKSUM(NEWID()) which returns an integer, then apply modulo and absolute value to get a range.
Example: random integer 1-100 per row:
SELECT ABS(CHECKSUM(NEWID())) % 100 + 1 AS RandomNumber FROM YourTable;
Why this works: NEWID() generates a unique GUID per row, CHECKSUM() converts it to an integer (can be negative), ABS() makes it positive, modulo 100 gives 0-99, then +1 gives 1-100. This is the standard approach for per-row randomness.
Note: CHECKSUM(NEWID()) can return the same value for different rows rarely, but it’s acceptable for most uses. If you need a random float per row, use RAND(CHECKSUM(NEWID())) as a seed, but that is slower.
Choosing Between RAND() and NEWID()
- Single random value (e.g., one random number for a session): Use
RAND(). - Random value per row in a query: Use
CHECKSUM(NEWID()). - Random ordering (e.g., pick a random row): Use
ORDER BY NEWID(). - Reproducible random sequence (e.g., testing): Use
RAND(seed).
For sampling a random row from a table, SELECT TOP 1 * FROM YourTable ORDER BY NEWID(); is simple but can be slow on large tables because it sorts the entire table. For better performance, use a random number column or the TABLESAMPLE clause (though TABLESAMPLE is not truly random per row).
Common Pitfalls and Misconceptions
Misconception: RAND() returns a different value for each row. As noted, it doesn’t in a single statement. Many beginners write SELECT FLOOR(RAND()*10)+1 FROM sys.objects and get the same number repeated. Use CHECKSUM(NEWID()) instead.
Pitfall: Using modulo with CHECKSUM(NEWID()) can produce a slight bias. Because CHECKSUM() returns a 32-bit integer, the modulo operation can be slightly non-uniform if the range does not evenly divide 2^32. For most applications, this bias is negligible. For cryptographic-quality randomness, use CRYPT_GEN_RANDOM() (available in SQL Server 2008 and later) which generates a random byte string.
Pitfall: RAND() with a seed in a loop. If you call RAND(seed) repeatedly with the same seed, you get the same value. To get a sequence, use RAND() without a seed in a loop, but note that the sequence is deterministic per session.
Pitfall: Using NEWID() in a WHERE clause. For example, WHERE NEWID() < 0.5 will evaluate once per row, but it’s inefficient and can lead to unexpected results. Better to use ORDER BY NEWID() or a pre-generated random column.
Performance and Cost Considerations
RAND() is very fast because it’s a simple mathematical function. CHECKSUM(NEWID()) requires generating a GUID and computing a checksum, which is slightly more expensive but still acceptable for moderate row counts (up to millions). For very large tables, sorting by NEWID() can be costly because it requires a full sort. Alternatives include:
- Using a pre-generated random number column (e.g., a column with random floats) and selecting based on that.
- Using
TABLESAMPLEfor approximate sampling, but it does not guarantee uniform randomness. - Using
CRYPT_GEN_RANDOM()for cryptographic randomness, which is slower but more secure.
For a single random row from a large table, consider using SELECT TOP 1 * FROM YourTable WHERE ID >= (SELECT FLOOR(RAND() * (SELECT MAX(ID) FROM YourTable))) but this assumes an identity column and can miss rows if IDs are not contiguous.
Alternatives and Advanced Techniques
CRYPT_GEN_RANDOM(): Generates a random binary value. To get a random integer, convert to int: SELECT ABS(CONVERT(int, CRYPT_GEN_RANDOM(4)) % 100) + 1. This is more uniform and secure, but slower.
RAND() with CHECKSUM(NEWID()) as seed: SELECT RAND(CHECKSUM(NEWID())) gives a float per row, but it’s slower than direct CHECKSUM.
Using a numbers table: If you need many random numbers, generate them in a loop or use a tally table, but per-row randomness is usually fine.
Randomizing a whole table: Add a column with random values using UPDATE YourTable SET RandomCol = RAND(CHECKSUM(NEWID())) but note that RAND() with a seed per row is not truly random because the seed is based on the row’s checksum, which is deterministic. Better to use CHECKSUM(NEWID()) directly.
For ordering, ORDER BY NEWID() is the simplest but not the most efficient. Consider using a random column with an index if you need to select a random subset frequently.
Frequently Asked Questions
How do I generate a random number between 1 and 100 in SQL Server? Use SELECT FLOOR(RAND() * 100) + 1; for a single value, or SELECT ABS(CHECKSUM(NEWID())) % 100 + 1 FROM YourTable; for per-row values.
Why does RAND() return the same value for every row in my query? Because SQL Server evaluates RAND() once per statement, not per row. Use CHECKSUM(NEWID()) to get a different value per row.
Can I use RAND() to pick a random row from a table? Yes, but not directly. Use ORDER BY NEWID() to shuffle and pick the top 1, or use a random number column and select a value. For large tables, ORDER BY NEWID() can be slow.
Is there a way to generate a random number that is cryptographically secure? Yes, use CRYPT_GEN_RANDOM(). For example, SELECT ABS(CONVERT(int, CRYPT_GEN_RANDOM(4)) % 100) + 1; gives a random integer 1-100 with better uniformity.
How do I generate a random decimal between 0 and 1 per row? Use SELECT RAND(CHECKSUM(NEWID())) FROM YourTable; but note this is slower. Alternatively, use ABS(CHECKSUM(NEWID())) / 2147483648.0 to get a float between 0 and 1.
What is the difference between RAND() and NEWID()? RAND() returns a float and is deterministic with a seed; NEWID() returns a GUID and is unique per call. For per-row random numbers, NEWID() is used because it changes per row.
Related
- How to Select a Cell and Everything Below It in Excel
- SQL Difficult Queries: Real-World Examples & Solutions
- Switch Desktop Shortcut: How to Create & Use It
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Delete a Page in Word After a Page Break: Step-by-StepTo delete a blank page after a page break in Word, show formatting marks, find the page break…
- Find an Excel Password in a Protected File? Safe OptionsYou usually cannot find or reveal a password from inside a protected Excel file: Excel does not display…
- Excel Consolidate Tabs: Methods for Combining WorksheetsTo consolidate Excel tabs, use Data > Consolidate when you want to summarize matching ranges, or use Power…
- Merge Cells in Excel and Keep All DataTo merge cells in Excel without losing their contents, first combine the contents into one cell, then merge…
- Excel Import CSV Into a Sheet: Steps, Options, and FixesTo import a CSV file into an Excel sheet, select Data > From Text/CSV, choose the file, check…
- Excel Power Query Pattern Matching: Methods and ExamplesExcel Power Query pattern matching means filtering or transforming values according to text rules such as “contains this…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.