Thursday, March 12, 2020

How to get random rows in SQL? SQL Query to get Random data. Top N Random Records.

There are a number of ways to get Random data from database. Following are some examples that works without any extra algorithm:

SQL Server:

SELECT TOP 20 *
FROM table_name
ORDER BY NEWID()

MySQL:

SELECT *
FROM table_name
ORDER BY RAND()
LIMIT 20



PostgreSQL:

SELECT *
FROM table_name
ORDER BY RANDOM()
LIMIT 20

Oracle:

SELECT *  FROM
( SELECT *
FROM table_name
ORDER BY dbms_random.value )
WHERE rownum <= 20











No comments:

Post a Comment

Please keep your comments relevant.
Comments with external links and adult words will be filtered.