SQL ORDER BY RANDOM

The ORDER BY RANDOM clause allows you to sort your result set in a random order. This is particularly useful when you need to return a random sample of records from a database, such as selecting random products, users, or any other data.

Different database management systems use different functions to achieve random ordering. For example, MySQL uses RAND(), while PostgreSQL uses RANDOM().

Example

The following example will sort the products randomly.

Code Example


-- Sorting products randomly
SELECT Product, Price
FROM Orders
ORDER BY RAND();
            

Output

Product Price
Phone 800.00
Laptop 1200.00
Tablet 600.00

Explanation

- The query selects the Product and Price columns from the Orders table.
- The ORDER BY RAND() sorts the result set in a random order.

This is useful when you want to show a random selection of products, such as in a "featured products" section or a random offer display.