To create a random number in SQL, use the RAND() function. In most SQL databases, RAND() returns a floating-point value between 0 (inclusive) and 1 (exclusive), such as 0.7342. To get a random integer in a specific range, combine RAND() with arithmetic: FLOOR(RAND() * (max - min + 1)) + min. For example, SELECT FLOOR(RAND() * 100) + 1; returns a random integer from 1 to 100.
How RAND() Works in Different SQL Dialects
The core concept is the same across major databases, but the exact syntax and behavior vary slightly. Here’s a breakdown of the most common implementations:
- MySQL / MariaDB:
RAND()returns a random float in [0,1). You can provide a seed:RAND(42)produces a repeatable sequence. To get an integer between 1 and 10:FLOOR(RAND() * 10) + 1. - PostgreSQL: Uses
RANDOM()instead ofRAND(). It returns a float in [0,1). For a random integer 1-10:FLOOR(RANDOM() * 10 + 1)::int. PostgreSQL does not support a seed argument directly; you’d useSETSEED()to make sequences repeatable. - SQL Server (T-SQL):
RAND()works like MySQL, but note thatRAND()is evaluated once per row in a query, not per row unless you useNEWID()for a more random per-row value. For a random integer 1-10:FLOOR(RAND() * 10) + 1. - SQLite: Uses
RANDOM()which returns a 64-bit integer between -9223372036854775808 and +9223372036854775807. To get a random number between 1 and 10, useABS(RANDOM() % 10) + 1. - Oracle: Uses
DBMS_RANDOM.VALUEto get a float between 0 and 1, orDBMS_RANDOM.VALUE(low, high)for a number in a range. For an integer, wrap withFLOOR.
Generating a Random Integer in a Range
The most common need is a random integer between two bounds, say 1 and 100. The formula FLOOR(RAND() * (max - min + 1)) + min works in MySQL, SQL Server, and others. Here’s why: RAND() gives a float from 0 to 0.9999… Multiplying by 100 gives 0 to 99.9999…, then FLOOR gives 0 to 99, then adding 1 gives 1 to 100. If you want a range like 5 to 15, use FLOOR(RAND() * 11) + 5 because 15-5+1 = 11. Always double-check the math to avoid off-by-one errors.
Random Rows from a Table (Sampling)
Often you want to retrieve random rows from a table, not just a single number. The method varies by database:
- MySQL:
SELECT * FROM table ORDER BY RAND() LIMIT 5;– this is simple but slow on large tables because it sorts the entire table. - PostgreSQL:
SELECT * FROM table ORDER BY RANDOM() LIMIT 5;– same performance caveat. - SQL Server:
SELECT TOP 5 * FROM table ORDER BY NEWID();–NEWID()generates a GUID per row, which is more random thanRAND()which is evaluated once per query. - SQLite:
SELECT * FROM table ORDER BY RANDOM() LIMIT 5;– works, but again sorts the whole table.
For large tables, a more efficient approach is to generate a random ID and fetch that row, or use a tablesample (PostgreSQL, SQL Server) if you need a percentage of rows.
Common Misconception: RAND() in a WHERE Clause
A frequent mistake is trying to use RAND() in a WHERE clause to filter random rows, like WHERE RAND() > 0.5. In MySQL, this actually works (each row gets a random value), but it’s not always efficient. In SQL Server, RAND() is evaluated only once per query, so WHERE RAND() > 0.5 will either return all rows or none, depending on the single random value. If you need a random subset, use ORDER BY NEWID() or TABLESAMPLE instead.
Seeding for Reproducibility
Sometimes you need the same random sequence for testing or debugging. In MySQL, RAND(seed) produces a repeatable sequence: SELECT RAND(123); always returns the same value. In SQL Server, RAND(seed) works similarly. In PostgreSQL, use SELECT SETSEED(0.5); before calling RANDOM() – the seed is a float between -1 and 1. Note that seeding is session-specific; it doesn’t affect other connections.
Performance and Alternatives
Using ORDER BY RAND() on a large table is notoriously slow because it requires a full sort. For tables with millions of rows, consider these alternatives:
- Use a random ID: If your table has an auto-increment primary key, get a random ID with
SELECT FLOOR(RAND() * (SELECT MAX(id) FROM table)) + 1and then fetch that row. This is fast but can miss rows if IDs have gaps. - TABLESAMPLE (SQL Server, PostgreSQL):
SELECT * FROM table TABLESAMPLE (10 PERCENT);gives a random sample without sorting, but it’s not perfectly uniform and may not work on all table types. - Precomputed random numbers: Add a column with a pre-generated random value and index it, then select from that.
Frequently Asked Questions
How do I get a random decimal between 0 and 1?
Simply use RAND() (or RANDOM() in PostgreSQL/SQLite). It returns a float from 0 (inclusive) to 1 (exclusive). If you need a decimal with more precision, it’s already as precise as the database allows.
Why does RAND() return the same value every time in SQL Server?
In SQL Server, RAND() is evaluated only once per query, not per row. If you call it in a SELECT list, it returns the same value for every row. To get a different value per row, use NEWID() or combine RAND() with a per-row value like RAND(CHECKSUM(NEWID())).
Can I use RAND() to generate a random date?
Yes. Generate a random number of days and add it to a base date. For example, in MySQL: SELECT DATE_ADD('2020-01-01', INTERVAL FLOOR(RAND() * 365) DAY); gives a random date within a year. In PostgreSQL: SELECT DATE '2020-01-01' + (FLOOR(RANDOM() * 365) || ' days')::interval;
Is RAND() cryptographically secure?
No. RAND() is a pseudo-random number generator, not suitable for security purposes like generating passwords or tokens. For secure randomness, use database-specific functions like RANDOM_BYTES() in PostgreSQL, CRYPT_GEN_RANDOM() in SQL Server, or RANDOM_BYTES() in MySQL 8.0+.
How do I get a random row from a table without sorting?
If your table has a numeric primary key, you can generate a random ID and select that row. For example, in MySQL: SELECT * FROM table WHERE id = FLOOR(RAND() * (SELECT MAX(id) FROM table)) + 1; This is fast but may return no row if the ID doesn’t exist. Alternatively, use a join with a random offset, but that’s more complex.
Related
- Auto Sum Shortcut in Excel: Quick Keys & Steps
- Computer Data Entry Job Vacancy: Real Answers
- How to Select a Cell and Everything Below It in Excel
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Shortcut to Exit Window? Quick Keys & FixesThe quickest shortcut to exit a window in Windows is Alt+F4 on a PC, or Command+W on a…
- How to Access Shared Google SheetsTo access a shared Google Sheet, open the link the owner sent you while signed in to the…
- R44 Button Cell Batteries: Sizes, Equivalents & SafetyAn R44 button cell battery is a 1.55-volt silver oxide coin cell, also known as SR44, AG13, LR44,…
- Excel Custom Number Format: Show Zero as a DashYes. In Excel for Microsoft 365 on Windows, select the cells, press Ctrl+1, choose Custom, and enter #,##0.00;(#,##0.00);"-";@…
- How to Get Out of Track Changes Mode in Microsoft WordTo get out of Track Changes mode in Word, open the Review tab and turn off Track Changes.…
- Excel Cell Adjustment Shortcut: Resize Rows and ColumnsIn Excel for Microsoft 365 on Windows, use Alt, H, O, I to AutoFit a column to its…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.