To generate a random number in T-SQL, use the RAND() function for a decimal between 0 and 1, or combine it with arithmetic for integers. For a random integer in a specific range, the common pattern is FLOOR(RAND()*(max-min+1))+min, but be aware of pitfalls with row-by-row evaluation.
Background: Why Random Numbers in SQL Server?
Random numbers appear in many database tasks: sampling rows for testing, generating dummy data, assigning random priorities, or creating randomized passwords. T-SQL provides several built-in functions, each with different behavior regarding seed values, distribution, and performance. Understanding the differences helps you choose the right tool for your query.
How RAND() Works
RAND() returns a float from 0 (inclusive) to 1 (exclusive). Without a seed, it uses a random seed based on the system clock. With a seed (e.g., RAND(42)), it returns a repeatable sequence—useful for reproducible tests. However, RAND() is evaluated once per query, not per row, unless you provide a per-row seed like RAND(CHECKSUM(NEWID())). This is a common source of confusion: SELECT RAND() FROM sys.objects returns the same value for every row, not different values.
Generating Random Integers in a Range
To get an integer between @min and @max inclusive, use:
FLOOR(RAND()*(@max-@min+1))+@min
For example, to get a random number between 1 and 10:
SELECT FLOOR(RAND()*10)+1 AS RandomNumber;
This works because RAND() returns a value in [0,1), multiplying by 10 gives [0,10), FLOOR gives integers 0-9, and adding 1 shifts to 1-10. If you need a per-row random integer, combine with NEWID():
SELECT FLOOR(RAND(CHECKSUM(NEWID()))*10)+1 AS RandomNumber FROM sys.objects;
Here, NEWID() generates a unique GUID per row, CHECKSUM converts it to an integer seed, and RAND(seed) produces a distinct value for each row.
Using NEWID() for Random Ordering
To shuffle rows, the simplest method is ORDER BY NEWID(). This assigns a random GUID to each row and sorts by it. For example:
SELECT TOP 5 * FROM Employees ORDER BY NEWID();
This is easy to write, but for large tables it can be slow because it requires a sort of the entire result set. An alternative is to use CHECKSUM(NEWID()) as a random number per row, but be aware that CHECKSUM can return the same value for different GUIDs, causing ties in ordering.
Choosing the Right Method
Consider these factors:
- Single value vs. per row: For one random number,
RAND()is fine. For per-row values, useRAND(CHECKSUM(NEWID())). - Repeatability: If you need the same sequence for testing, use
RAND(seed)with a fixed seed. - Performance:
ORDER BY NEWID()is O(n log n) due to sorting. For large tables, consider usingTABLESAMPLEor a random number column with an index. - Distribution:
RAND()is uniformly distributed, butCHECKSUM(NEWID())may have slight biases; for most purposes it’s acceptable.
Common Pitfalls and Solutions
One common mistake is using RAND() in a WHERE clause expecting a different value per row. For example, WHERE RAND() < 0.5 evaluates once for the whole query, so it either selects all rows or none. To filter randomly per row, use WHERE CHECKSUM(NEWID()) % 2 = 0 (or similar). Another pitfall is generating a random number in a loop without reseeding—RAND() called rapidly can return the same value. In such cases, use RAND(CHECKSUM(NEWID())) or a different seed each iteration.
Alternatives: CRYPT_GEN_RANDOM and TABLESAMPLE
For cryptographic-quality randomness, use CRYPT_GEN_RANDOM(n), which returns n random bytes. To get an integer from it, you can use CONVERT(INT, CRYPT_GEN_RANDOM(4)) but that can be negative. A safer approach is to use ABS(CHECKSUM(CRYPT_GEN_RANDOM(4))) and then take modulo. For sampling rows, TABLESAMPLE returns a random subset of rows, but it is not guaranteed to be exactly the number you request and may return zero rows for small tables.
Frequently Asked Questions
How do I generate a random number between 1 and 100 in T-SQL?
Use SELECT FLOOR(RAND()*100)+1; for a single value, or SELECT FLOOR(RAND(CHECKSUM(NEWID()))*100)+1 FROM YourTable; for per-row values.
Why does RAND() return the same number for every row?
Because RAND() is evaluated once per query, not per row. To get different values per row, provide a seed based on a per-row value like RAND(CHECKSUM(NEWID())).
Can I use RAND() to select a random row?
Yes, but not directly. Use ORDER BY NEWID() or a per-row random number in a subquery. For example: SELECT TOP 1 * FROM Table ORDER BY NEWID();
Is RAND() cryptographically secure?
No. RAND() is a pseudo-random number generator and not suitable for security-sensitive tasks. Use CRYPT_GEN_RANDOM for generating passwords or encryption keys.
How can I generate a random decimal between 0 and 1?
Simply use RAND(). It returns a float between 0 and 1. For a different range, multiply and add: RAND()*(max-min)+min.
What is the difference between RAND() and NEWID()?
RAND() returns a float random number; NEWID() returns a uniqueidentifier (GUID). They serve different purposes: RAND() for numeric randomness, NEWID() for unique identifiers and shuffling rows.
Related
- Windows Zoom Out Shortcut Keys: Full Guide
- Generate Random Numbers in MATLAB: randi, rand & More
- Online Computer Skills Courses for Data Entry
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Pay Off Debt Snowball Spreadsheet: Build One in ExcelYes—a debt snowball spreadsheet can help you list balances from smallest to largest, track payments, and see when…
- Excel Time From Datetime: Extract the Time ValueIf a real Excel date-and-time value is in A2, use =MOD(A2,1) to extract its time portion, then format…
- Nested Dropdowns in Google Sheets: How to Set Them UpYes. You can make a nested, or dependent, dropdown in Google Sheets by making the choices in a…
- How to Enter Notes in PowerPoint: A Clear Step-by-Step GuideTo enter notes in PowerPoint, open your presentation in Normal view, show the Notes pane beneath the slide,…
- How to Insert a Straight Line in Word: 3 Easy MethodsTo insert a straight line in Word, use the Insert tab’s Shapes tool and hold Shift while you…
- Excel or Google Sheets? Features, Costs, and Trade-OffsExcel and Google Sheets are spreadsheet programs for organizing data, calculating results, and making charts, but they suit…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.