To generate a random number in 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 range, use FLOOR(RAND() * (max - min + 1)) + min. For random rows or unique random values, SQL Server offers NEWID(), and other databases have their own functions like RANDOM() in PostgreSQL.
Why You Need Random Numbers in SQL
Random numbers appear in many database tasks: sampling data for testing, assigning random discounts, shuffling quiz questions, generating temporary passwords, or splitting a dataset into random groups. Each use case has different requirements—some need a single random value, others need a random value per row, and some need uniqueness or cryptographic security. Knowing which function to use depends on your database system and the exact need.
Core Functions by Database
Different SQL dialects implement randomness differently. Here are the most common:
- SQL Server / T-SQL:
RAND()returns a float from 0 to 1.NEWID()returns a GUID; usingCHECKSUM(NEWID())gives a random integer. For a random row, useORDER BY NEWID(). - PostgreSQL:
RANDOM()returns a double precision between 0 and 1.ORDER BY RANDOM()picks random rows. - MySQL / MariaDB:
RAND()works similarly.ORDER BY RAND()is common but slow on large tables. - Oracle:
DBMS_RANDOM.VALUEreturns a number between 0 and 1, or between two bounds.DBMS_RANDOM.STRINGgenerates random strings. - SQLite:
RANDOM()returns a 64-bit integer (can be negative). UseABS(RANDOM() % (max - min + 1)) + minfor a range.
Generating an Integer in a Range
The most common request is a random integer between a minimum and maximum. The generic formula is:
FLOOR(RAND() * (max - min + 1)) + min
For example, to get a random number from 1 to 100 in SQL Server:
SELECT FLOOR(RAND() * 100) + 1 AS RandomNumber;
This works because RAND() returns a value in [0,1). Multiplying by 100 gives [0,100), flooring gives 0–99, then adding 1 gives 1–100. In PostgreSQL, use FLOOR(RANDOM() * 100) + 1. In SQLite, the integer function needs a different approach because RANDOM() returns negative values; use ABS(RANDOM() % 100) + 1.
Random Value Per Row
A common mistake is expecting RAND() to produce a different value for each row in a SELECT. In SQL Server, RAND() is evaluated once per statement, so every row gets the same value. To get a different random number per row, combine RAND() with a row-specific value, such as CHECKSUM(NEWID()):
SELECT ProductID, ABS(CHECKSUM(NEWID())) % 100 AS RandomDiscount FROM Products;
Here, CHECKSUM(NEWID()) generates a random integer per row, and the modulo gives a number between 0 and 99. In PostgreSQL, RANDOM() is evaluated per row, so SELECT id, RANDOM() FROM table works naturally. MySQL also evaluates RAND() per row.
Selecting Random Rows
To fetch a random sample of rows, you can order by a random value and limit the result. In SQL Server:
SELECT TOP 10 * FROM Employees ORDER BY NEWID();
In PostgreSQL and SQLite:
SELECT * FROM Employees ORDER BY RANDOM() LIMIT 10;
In MySQL:
SELECT * FROM Employees ORDER BY RAND() LIMIT 10;
Be aware that ORDER BY RAND() or RANDOM() scans the entire table and sorts it, which can be slow on large tables. For big datasets, consider using a random primary key offset or the TABLESAMPLE clause (SQL Server, PostgreSQL) for performance.
Common Pitfalls and Misconceptions
Several issues trip up developers:
- Same value for all rows: As noted,
RAND()in SQL Server is constant per query. UseNEWID()or a per-row seed. - Inclusive vs exclusive bounds:
RAND()never returns exactly 1, soFLOOR(RAND() * (max - min + 1)) + minincludes both min and max. If you useCEILINGorROUND, you might get an off-by-one error. - Negative numbers: In SQLite,
RANDOM()can be negative; using modulo directly gives negative results. UseABS(). - Non-uniform distribution: Using
ABS(CHECKSUM(NEWID())) % Ncan introduce slight bias because the range of CHECKSUM may not divide evenly by N. For most purposes it’s fine, but for strict uniformity, useRAND()with a floating-point conversion. - Security:
RAND()andNEWID()are not cryptographically secure. Do not use them for passwords, tokens, or any security-sensitive value. UseCRYPT_GEN_RANDOM()in SQL Server,gen_random_uuid()in PostgreSQL, orRANDOM_BYTES()in MySQL.
Performance Considerations
Random ordering is expensive because it requires a full sort. On a table with millions of rows, ORDER BY NEWID() can be very slow. Alternatives include:
- Select a random key value and fetch rows after that key.
- Use
TABLESAMPLEin SQL Server or PostgreSQL, which samples pages directly. - Pre-generate a random number column and index it, then pick a random value from that column.
For example, in SQL Server, you can do:
SELECT * FROM Employees TABLESAMPLE (10 PERCENT);
This returns approximately 10% of rows, but not exactly 10, and it’s fast because it doesn’t sort.
Frequently Asked Questions
How do I get a random number between 1 and 10 in SQL? Use FLOOR(RAND() * 10) + 1 in SQL Server/MySQL, FLOOR(RANDOM() * 10) + 1 in PostgreSQL, and ABS(RANDOM() % 10) + 1 in SQLite.
Why does RAND() return the same number for every row? In SQL Server, RAND() is evaluated once per query, not per row. To get a different value per row, use NEWID() or CHECKSUM(NEWID()).
Can I use RAND() to generate a random password? No, RAND() is not cryptographically secure. Use database-specific secure functions like CRYPT_GEN_RANDOM() in SQL Server or gen_random_bytes() in PostgreSQL.
How do I select a random row from a table? Use ORDER BY NEWID() in SQL Server, ORDER BY RANDOM() in PostgreSQL/SQLite, or ORDER BY RAND() in MySQL, all with LIMIT 1 or TOP 1.
Is ORDER BY RAND() slow? Yes, on large tables it sorts the entire table. Use TABLESAMPLE or a random key approach for better performance.
How do I generate a random decimal between 0 and 1? Simply use RAND() in SQL Server/MySQL, RANDOM() in PostgreSQL/SQLite, or DBMS_RANDOM.VALUE in Oracle.
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
- Close Multiple Windows in Excel: Keep Workbooks OpenTo close multiple Excel windows without closing a workbook, close each window separately: save any changes, select a…
- Excel Compare Two Sheets Side by Side: Practical MethodsTo view two Excel sheets beside each other, open both views, then choose View > View Side by…
- Kitchen Prep List Excel Template: Build a Clear SheetA kitchen prep list Excel template is a task table for tracking what must be prepared, in what…
- Excel Reverse Undo Shortcut: What Works and What Doesn’tIn Excel for Microsoft 365 on Windows, the shortcut that reverses an undo is Ctrl+Y; Excel calls this…
- Can You Add Search to an Excel Slicer? How It WorksYes. In Excel for Microsoft 365 on Windows, click the magnifying-glass icon in a slicer’s header, type part…
- Excel Shortcut to Select an Entire ColumnIn Excel for Microsoft 365 on Windows, press Ctrl+Spacebar to select the entire worksheet column containing the active…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.