SQL SELECT RANDOM: Fetching Random Rows from a Database
Selecting random rows is a common requirement in applications such as online exams, quizzes, and content recommendations. SQL lets us fetch random records efficiently, but the syntax varies across database systems. Let us explore how to do it in the most popular databases.
Complete Python Course with Advance topics:-
SQL Tutorial:-
Random Row in MySQL
SELECT product_name
FROM products
ORDER BY RAND()
LIMIT 1;
RAND() generates a random number for each row, and LIMIT 1 returns a single random row.
Random Row in Microsoft SQL Server
SELECT TOP 1 customer_name
FROM customers
ORDER BY NEWID();
Random Row in Oracle
SELECT employee_name FROM (
SELECT employee_name FROM employees
ORDER BY dbms_random.value
) WHERE ROWNUM = 1;
Random Row in PostgreSQL
SELECT book_title
FROM books
ORDER BY RANDOM()
LIMIT 1;
Performance Tip
On large tables, ORDER BY RAND() is slow because it assigns a random value to every row and sorts them all. For big datasets, consider fetching a random ID range or using TABLESAMPLE (where supported) for much better performance.
Download New Real Time Projects:- Click here
Complete Advance AI topics:-
Conclusion
Selecting random rows is a powerful technique. Each database has its own approach ÔÇö RAND() in MySQL, NEWID() in SQL Server, dbms_random in Oracle, and RANDOM() in PostgreSQL. For more SQL tips, stay tuned to .
how to select random rows in sql
sql select random number between range
sql random sample n rows
order by random sql
mysql select random
sql server newid random
sql select random row
sql select random w3schools