Yes, SQL Server can generate random numbers using the RAND() function, and for more control or integer ranges, you combine it with arithmetic or use NEWID() for a different distribution. The simplest call, SELECT RAND();, returns a float between 0 and 1, but you’ll often need integers or unique values, which requires a bit more logic.
How RAND() Works in T-SQL
RAND() is a built-in function that returns a pseudo-random float value from 0 inclusive to 1 exclusive (0.0 to 0.999…). It’s deterministic when given a seed: RAND(10) always returns the same sequence starting from that seed. Without a seed, SQL Server uses a random seed based on the system’s time, so each call is different.
Key points:
RAND()is evaluated once per row in a query, but if you call it multiple times in the same expression, it may return the same value because the optimizer might evaluate it once.- It’s not cryptographically secure; use it for testing or non-security purposes.
- To get an integer in a range, use the formula:
FLOOR(RAND() * (max - min + 1)) + min.
Generating a Random Integer in a Range
The most common need is a random integer between two bounds, say 1 and 100. The standard pattern is:
SELECT FLOOR(RAND() * (100 - 1 + 1)) + 1 AS RandomInt;
This works because RAND() gives a decimal less than 1, multiplying by the range size (100) gives a number from 0 to 99.999, FLOOR rounds down to 0–99, then adding the minimum (1) shifts it to 1–100.
For a general formula with variables:
DECLARE @Min INT = 5, @Max INT = 15;
SELECT FLOOR(RAND() * (@Max - @Min + 1)) + @Min AS RandomInRange;
Be careful: if you use RAND() inside a SELECT that returns many rows, each row gets a different value because the function is evaluated per row. But if you need the same random number for all rows (e.g., for a batch), assign it to a variable first.
Using NEWID() for Randomness and Uniqueness
NEWID() creates a globally unique identifier (GUID) that is highly random. To get a random integer from it, you can use the checksum of the GUID, then apply modulo to fit a range. Example:
SELECT ABS(CHECKSUM(NEWID())) % 100 + 1 AS RandomInt;
This generates a random integer between 1 and 100. The ABS ensures a positive number (since CHECKSUM can be negative), and the modulo restricts the range. Note that modulo introduces a slight bias if the range doesn’t divide evenly into the maximum checksum value, but for most uses it’s acceptable.
Unlike RAND(), NEWID() is evaluated per row and gives a different value each time, even in the same expression. It’s also more random in practice, though still not cryptographically secure.
Choosing Between RAND and NEWID
Both functions serve different purposes:
- RAND(): Simple, fast, and fine for most non-critical random numbers. It’s deterministic with a seed, which is useful for reproducible tests.
- NEWID(): Better when you need a unique value per row or a more unpredictable sequence. It’s also useful for random ordering, e.g.,
ORDER BY NEWID()to shuffle rows.
If you need a random sample of rows, use ORDER BY NEWID() with TOP n, but be aware it scans the whole table and can be slow on large tables. For large tables, consider using TABLESAMPLE or a random key range.
Common Problems and Misconceptions
One frequent issue: using RAND() in a WHERE clause can cause unexpected results because the function might be evaluated multiple times, giving different values for the same row. For example, WHERE RAND() < 0.5 might not return exactly half the rows because each comparison is independent.
Another misconception is that RAND() is truly random. It’s pseudo-random, meaning it follows a deterministic algorithm. If you need cryptographic randomness (e.g., for passwords or tokens), use CRYPT_GEN_RANDOM() instead, which uses the Windows Crypto API.
Also, beware of integer overflow when using large ranges. If @Max - @Min + 1 exceeds 2^31-1, the arithmetic may overflow. Use BIGINT or a different approach.
Performance and Efficiency Considerations
Generating random numbers is generally fast, but there are performance implications when used in large queries:
ORDER BY NEWID()on a large table requires sorting, which is expensive. For sampling, consider usingTABLESAMPLEor a random modulus on a key column.- If you need many random numbers, generate them in a loop or use a numbers table, rather than calling
RAND()repeatedly in a loop, which is slower. - For bulk operations, consider using a set-based approach with
NEWID()in aSELECTto assign random values to each row.
Alternatives and Advanced Techniques
For more controlled randomness, you can use CRYPT_GEN_RANDOM() for secure random bytes. Example to get a random integer between 1 and 100:
DECLARE @RandomInt INT;
SET @RandomInt = ABS(CAST(CRYPT_GEN_RANDOM(4) AS INT)) % 100 + 1;
This uses 4 random bytes and converts to an integer. It’s slower but cryptographically secure.
If you need a random date, combine RAND() with date arithmetic: DATEADD(day, FLOOR(RAND() * 3650), '2020-01-01') gives a random date within 10 years.
For random strings, you can use NEWID() and strip hyphens, or use a custom function with a character set.
Frequently Asked Questions
How do I generate a random number between 1 and 10 in SQL Server?
Use SELECT FLOOR(RAND() * 10) + 1; or SELECT ABS(CHECKSUM(NEWID())) % 10 + 1;. Both return an integer from 1 to 10 inclusive.
Why does RAND() return the same value for every row in a SELECT?
If you call RAND() without a seed in a single statement, SQL Server may evaluate it once and reuse the value for all rows. To get a different value per row, use NEWID() or add a seed that changes per row, like RAND(ROW_NUMBER() OVER (ORDER BY ...)).
Can I use RAND() for passwords or security tokens?
No, RAND() is not cryptographically secure. Use CRYPT_GEN_RANDOM() or generate random values in application code with a secure random number generator.
How to get a random row from a table?
Use SELECT TOP 1 * FROM table ORDER BY NEWID();. For large tables, this is slow; consider using TABLESAMPLE or a random key range.
Is there a way to make RAND() produce a random decimal between 1 and 100?
Yes, simply multiply: SELECT RAND() * 100 + 1; gives a float between 1.0 and 101.0 (exclusive of 101). For inclusive, use RAND() * 99 + 1 for 1 to 100.
Does SQL Server have a RANDOM function like in other languages?
SQL Server has RAND() and NEWID(), but no single function that returns a random integer directly. You combine them with arithmetic. For secure randomness, use CRYPT_GEN_RANDOM().
Related
- Python Random Numbers: How to Generate Them
- Data Entry Computer Course: What It Covers & Is It Worth It?
- Splitting Strings in Java: Methods and Examples
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Wrap Text in Google Sheets Without Cutting It OffTo wrap text in Google Sheets, select the cell or cells, then choose Format > Wrapping > Wrap.…
- Quicken Budget Spreadsheet: Build or Export a BudgetQuicken is personal-finance software, not a spreadsheet, so you do not need an Excel file to make a…
- Google Sheets: Lock Cells While Scrolling?No: Google Sheets cannot lock an arbitrary cell or range in place as you scroll. To keep headings…
- How to Change Your Name on Track Changes in Microsoft WordTo change the name Word attaches to new tracked edits, update the Office user name: in Word for…
- How to Make Two Numbered Columns in Microsoft WordTo make two numbered columns in Word, choose Layout > Columns > Two, then start or select one…
- How to Get Rid of Track Changes Lines in Microsoft WordTo hide the vertical lines that mark tracked edits, open the Review tab and choose Display for Review…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.