SQL SELECT RANDOM: Fetching Random Rows from a Database

SQL SELECT RANDOM
SQL SELECT RANDOM

SQL SELECT RANDOM

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 Advance AI Topics: Click Here
SQL Tutorial:
Click Here

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

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

Written by Rishabh Saini Founder, UpdateGadh

Rishabh Saini is the founder of UpdateGadh. He has 5 years of experience building PHP, Python, Java, AI and ML projects, and works on projects with the latest and trending technologies. He has helped 2,000+ BCA, MCA and B.Tech students with final year projects. Every project on UpdateGadh is built and tested by him before it is published.

Leave a Reply

Your email address will not be published. Required fields are marked *