The RAND() function generates a random decimal number.
Definition and Usage
- Returns a random number between 0 (inclusive) and 1 (exclusive).
- If a seed value is provided, the function returns a repeatable sequence of random numbers for that seed.
Syntax
RAND(seed)
Parameter Values
| Parameter | Description |
|---|---|
seed |
Optional. Specifies a seed value to produce a repeatable sequence of random numbers. |
Technical Details
- Introduced in: MySQL 4.0
- Return Value: A floating-point number between 0 and 1.
Examples
Example 1: Random decimal number (no seed)
SELECT RAND();
Output:
0.789435 (example output, varies on execution)
Example 2: Random decimal number with a seed
SELECT RAND(6);
Output:
0.197107 (always returns the same value for the seed 6)
Example 3: Random decimal number within a range
To generate a random number between 5 (inclusive) and 10 (exclusive):
SELECT RAND() * (10 - 5) + 5;
Output:
7.652934 (example output, varies on execution)
Example 4: Random integer within a range
To generate a random integer between 5 and 10 (both inclusive):
SELECT FLOOR(RAND() * (10 - 5 + 1) + 5);
Output:
8 (example output, varies on execution)
Use Cases
- Shuffling data: Use
RAND()to order rows randomly.
SELECT * FROM Products
ORDER BY RAND();
- Random sampling: Retrieve random rows from a table.
SELECT * FROM Customers
ORDER BY RAND()
LIMIT 5;
- Game or lottery systems: Generate random numbers for outcomes.
Related Functions
FLOOR(): Helps convert random decimals into integers.CEIL(): Rounds random numbers to the nearest greater integer.