Random Number in SQL: How to Generate and Use Them
In this article
To generate a random number in SQL, you use a built-in function—such as RAND() in SQL Server and MySQL or RANDOM() in PostgreSQL and SQLite—which returns a decimal value between 0 and 1. To get a whole number within a specific range, you multiply this decimal by the size of your range and use a rounding or floor function to convert it to an integer.
What You'll Need
- Access to a SQL database (such as MySQL, PostgreSQL, SQL Server, or SQLite).
- A query editor or database management tool (like MySQL Workbench, pgAdmin, or SQL Server Management Studio).
- Basic knowledge of
SELECTstatements and basic arithmetic operators.
Step-by-Step
-
Identify your SQL dialect.
Different database systems use different function names for randomness. Before writing your query, confirm which system you are using. For MySQL and SQL Server, the function is
RAND(). For PostgreSQL and SQLite, the function isRANDOM(). Using the wrong function will result in a "function does not exist" error. -
Generate a basic decimal.
Start by running a simple query to see the base output. In MySQL, run
SELECT RAND();. This will produce a value like0.458213. This value is a float that is always greater than or equal to 0 and less than 1. This is the foundation for all other random calculations. - Define your target range. Decide the minimum and maximum values you want. For example, if you want a random number between 1 and 100, your range size is 100. If you want a number between 50 and 150, your range size is also 100, but your starting offset is 50.
-
Apply the range formula.
To convert the 0-1 decimal into your desired range, use the formula:
(RAND() * (max - min + 1)) + min. For a number between 1 and 100, the logic is(RAND() * 100) + 1. The multiplication expands the 0-1 range to 0-100, and adding 1 shifts it to 1-101. -
Convert the decimal to an integer.
Because
RAND()returns a float, you must remove the decimals to get a whole number. In MySQL, useFLOOR():SELECT FLOOR(RAND() * 100) + 1;In SQL Server, useFLOOR()orCAST():SELECT FLOOR(RAND() * 100) + 1;In PostgreSQL, useFLOOR():SELECT FLOOR(RANDOM() * 100) + 1;TheFLOOR()function rounds down to the nearest whole number, ensuring you don't accidentally jump to the next integer higher than your maximum. -
Apply the random number to a table.
If you need a random number for every row in a table, include the function in your
SELECTlist. For example:SELECT name, FLOOR(RAND() * 100) + 1 AS random_score FROM users;This assigns a unique random number to every person in the list. -
Use randomness for sampling.
A common use case is selecting a random row from a table. Instead of generating a number, use the random function in the
ORDER BYclause. In MySQL:SELECT * FROM products ORDER BY RAND() LIMIT 1;In PostgreSQL:SELECT * FROM products ORDER BY RANDOM() LIMIT 1;This tells the database to assign a random value to every row and then sort the entire table by those values, effectively shuffling the data before picking the top result.
Common Mistakes
One of the most frequent errors is forgetting that RAND() and RANDOM() return a float. If you simply multiply RAND() * 10, you will get 7.4231 instead of 7. Always use FLOOR() or ROUND() to clean up the output.
Another mistake is using ORDER BY RAND() on very large tables. While this is the easiest way to get a random row, it is extremely slow on tables with millions of records. This is because the database must generate a random number for every single row and then sort the entire dataset in memory before it can give you the LIMIT 1 result. For large datasets, it is better to generate a random ID in your application code or use a filtered index.
Users also frequently confuse RAND() with NEWID() in SQL Server. While RAND() gives a number, NEWID() generates a unique GUID (Global Unique Identifier). If you need a completely unique string rather than a number, NEWID() is the correct choice.
Tips
To make your random numbers repeatable for testing purposes, use a seed. In SQL Server and MySQL, you can pass a number into the function: RAND(123). If you use the same seed, the function will produce the exact same sequence of "random" numbers every time. This is invaluable for debugging reports where you need the data to stay consistent while you fix a bug.
If you are working with PostgreSQL and need a random number within a specific range without doing the manual math, you can combine RANDOM() with a WHERE clause if you are picking from an existing set of IDs. However, for pure number generation, the FLOOR(RANDOM() * range) + min method remains the standard.
When updating a table with random values, be careful with UPDATE statements. If you run UPDATE users SET score = FLOOR(RAND() * 100), every user will get a different number. But if you use a variable to hold the random number first, every user will end up with the same number because the variable is only evaluated once.
Troubleshooting
If your query returns an error saying the function does not exist, double-check your SQL dialect. You are likely using RAND() in a PostgreSQL environment or RANDOM() in a MySQL environment. Switch to the correct function for your specific database engine.
If you find that ORDER BY RAND() is causing your application to time out or run slowly, stop using it immediately. Instead, find the maximum ID in your table SELECT MAX(id) FROM table, generate a random number between 1 and that maximum in your programming language (like Python or JavaScript), and then query for that specific ID. If the ID doesn't exist (due to gaps in the sequence), simply pick another random number or use WHERE id >= [random_number] LIMIT 1.
If your random numbers are always the same every time you run the query, check if you have accidentally included a constant seed inside the parentheses. Removing the seed (e.g., changing RAND(1) to RAND()) will restore true pseudo-randomness based on the system clock.
Frequently Asked Questions
Is the random number truly random?
No, SQL functions like RAND() produce pseudo-random numbers. They use a mathematical algorithm starting from a seed value. While they are sufficient for most business applications and sampling, they are not cryptographically secure and should not be used for high-security encryption keys.
How do I get a random number between 1 and 10?
Use the formula SELECT FLOOR(RAND() * 10) + 1;. The RAND() * 10 part creates a number between 0 and 9.999, FLOOR turns that into 0 through 9, and adding 1 shifts the final range to 1 through 10.
Can I generate a random boolean (True/False)?
Yes. The easiest way is to check if a random number is greater than 0.5. For example: SELECT CASE WHEN RAND() > 0.5 THEN 'True' ELSE 'False' END;
Why is my random column returning the same value for every row?
This usually happens if you calculate the random value in a variable or a subquery that the database optimizer treats as a constant. Ensure the random function is called directly within the SELECT or UPDATE statement for each row.
Does the random function work in a WHERE clause?
Yes, but be cautious. Using WHERE RAND() < 0.1 is a common way to return approximately 10% of the rows in a table. However, because this requires a full table scan, it can be slow on large datasets.