In this tutorial, you will learn how to sort the result set using the SQL ORDER BY clause and select random rows from the result set using database specific RANDOM function.
One question that can come to your mind that what is the need of selecting random rows from the result set?
Sometimes it may need to display random articles, products, or links to your user.
You need to use some function that does the work for you and select random rows from the database. The syntax and query can be a little bit different for different databases.
Selecting random row with ORACLE
If you want to select random rows with the ORACLE database, use the following code.
SELECT column FROM table ORDER BY dbms_random.value;
Selecting random row with SQL Server
SELECT column FROM table ORDER BY NEWID ();
Selecting random row with MYSQL
SELECT column FROM table ORDER BY RAND () ;
Selecting random row with Postgre SQL
SELECT column FROM table ORDER BY RANDOM () ;
Selecting random row using IBM DB2
SELECT column RAND () as IDX FROM table ORDER BY IDX;