In SQL, use FLOOR(RAND() * (max - min + 1)) + min for MySQL, MariaDB, or SQL Server, or FLOOR(RANDOM() * (max - min + 1)) + min for PostgreSQL and SQLite. This returns a random integer between min and max, inclusive on both ends.
Why the Formula Works
The core of any SQL random integer is a function that produces a decimal between 0 (inclusive) and 1 (exclusive). RAND() in MySQL and SQL Server, and RANDOM() in PostgreSQL and SQLite, both do exactly that. Multiplying that decimal by the width of your range (max - min + 1) gives a number from 0 up to just under the width. Adding min shifts it into your desired range, and FLOOR() rounds down to the nearest whole number. The +1 is critical: without it, the maximum value would never be generated because the random decimal never reaches 1.
Examples Across Major Databases
Here are concrete examples for a random integer between 5 and 10 (inclusive) in each common database:
- MySQL / MariaDB:
SELECT FLOOR(RAND() * (10 - 5 + 1)) + 5; - SQL Server:
SELECT FLOOR(RAND() * (10 - 5 + 1)) + 5;(same syntax) - PostgreSQL:
SELECT FLOOR(RANDOM() * (10 - 5 + 1)) + 5; - SQLite:
SELECT FLOOR(RANDOM() * (10 - 5 + 1)) + 5;(note: SQLite’s RANDOM() returns a 64-bit integer, so you must divide by a large number to get a decimal:SELECT FLOOR(ABS(RANDOM() % 6)) + 5;is simpler, or useCAST(RANDOM() AS REAL) / 9223372036854775807)
For SQLite, the cleanest approach is the modulo trick: SELECT ABS(RANDOM() % 6) + 5; where 6 is the range width (10-5+1). This avoids floating-point issues entirely.
How to Choose the Right Range
Decide whether you need inclusive or exclusive bounds. The formula above is inclusive of both min and max. If you need exclusive of max (e.g., 1 to 10 but never 10), drop the +1 inside the multiplication: FLOOR(RAND() * (max - min)) + min. If you need exclusive of min (rare), add 1 to the result. For most use cases—like picking a random row offset or a random ID—inclusive is what you want.
Using Random Numbers in Queries
You often need a random value per row, not just one value. In MySQL, RAND() is evaluated per row when used in a WHERE clause or SELECT list. For example, to assign a random score between 1 and 100 to each row in a table:
SELECT user_id, FLOOR(RAND() * 100) + 1 AS random_score FROM users;
In SQL Server, RAND() is evaluated once per query, so the same value appears on every row. To get a different value per row, combine it with CHECKSUM(NEWID()) or use ABS(CHECKSUM(NEWID())) % 100 + 1. In PostgreSQL, RANDOM() is evaluated per row by default, so it works naturally.
Common Pitfalls and Fixes
- Getting the same value repeatedly in SQL Server: Use
ABS(CHECKSUM(NEWID())) % (max - min + 1) + minfor per-row randomness. - Off-by-one errors: Always test with small ranges. For 1–3, the formula should never return 0 or 4.
- Negative ranges: The formula works with negatives. For -5 to 5, use
FLOOR(RAND() * 11) - 5. Be careful with modulo in SQLite—ABS(RANDOM() % 11) - 5gives 0 to 10 then subtracts 5, so it works. - Performance: Calling
RAND()millions of times in a large UPDATE can be slow. If you need many random numbers, generate them in a client language or use a numbers table.
Comparing with Other Approaches
Alternatives include using NEWID() in SQL Server (which is a GUID, not a number), or using a sequence of pseudo-random numbers from a seeded PRNG. For reproducible results (e.g., testing), you can seed RAND(seed) in MySQL and SQL Server. PostgreSQL’s SETSEED() does the same. But for most production uses, the built-in functions are sufficient. If you need cryptographic randomness (e.g., for a lottery), use database-specific functions like CRYPT_GEN_RANDOM() in SQL Server or gen_random_bytes() in PostgreSQL with the pgcrypto extension—these are not suitable for simple ranges.
Frequently Asked Questions
How do I get a random decimal between two numbers?
Use RAND() * (max - min) + min without FLOOR. For example, SELECT RAND() * 10 + 5 gives a decimal between 5 and 15 (exclusive of 15).
Can I use this in a WHERE clause to pick random rows?
Yes, but be careful. In MySQL, ORDER BY RAND() LIMIT 1 is common. In SQL Server, use ORDER BY NEWID(). For large tables, these are slow; consider selecting a random ID first.
Why does SQL Server give me the same number every row?
Because RAND() is evaluated once per query. Use ABS(CHECKSUM(NEWID())) % (max - min + 1) + min to get a different number per row.
How do I generate a random number in a stored procedure?
Exactly the same way—just put the formula in a variable: DECLARE @rand INT = FLOOR(RAND() * 100) + 1; in SQL Server, or SET @rand = FLOOR(RAND() * 100) + 1; in MySQL.
Is there a way to make the random number repeatable for testing?
Yes. In MySQL, SELECT RAND(42) gives the same sequence every time with seed 42. In SQL Server, RAND(42) works similarly. In PostgreSQL, use SELECT SETSEED(0.42); before your query.
Related
- Practice SQL Queries for Interview: 7 Core Topics
- Generate Random Number in Blue Prism: Full Guide
- Shortcut for Arrow? Best Ways to Type →
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Solver Limitations: What It Can and Cannot DoExcel Solver is best suited to small, well-structured optimization models: the standard Solver add-in can adjust at most…
- Monthly Schedule in Google Sheets: How to Build OneTo make a monthly schedule in Google Sheets, set up a sheet with a year and month, create…
- Cash Flow Forecast Template Excel: Free OptionsYes—free cash flow forecast templates for Excel are available from Microsoft Create and other spreadsheet providers, although the…
- Excel Page Break Preview Without Page Numbers: What to KnowIn Excel for Microsoft 365 on Windows, you cannot hide the large page-number labels while staying in Page…
- How to Set an Out of Office Reply in OutlookTo set an out of office reply in Outlook, open Automatic Replies for your email account, write your…
- Schedule an Email in Outlook: Step-by-Step GuideTo schedule a one-time email in Outlook, write your message, open the menu beside Send, choose Schedule send,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.