SQL ORDER BY RANDOM

If you want the resulting record to be ordered randomly, you should use the following codes according to several databases.

Here is a question: what is the need to fetch a random record or a row from a database?

Sometimes you may want to display random information like articles, links, pages, etc., to your user.

If you want to fetch random rows from any of the databases, you have to use some altered queries according to the databases.

  • Select a random row with MySQL:

If you want to return a random row with MY SQL, use the following syntax:

SELECT column FROM table ORDER BY RAND () LIMIT 1;   
  • Select a random row with Postgre SQL:
SELECT column FROM table ORDER BY RANDOM () LIMIT 1;  
  • Select a random row with SQL Server:
SELECT TOP 1 column FROM table ORDER BY NEWID ();    
  • Select a random row with oracle:
SELECT column FROM (SELECT column FROM table ORDER BY dbms_random.value) WHERE rownum = 1;   
  • Select a random row with IBM DB2:
SELECT column RAND () as IDX  FROM table ORDER BY  IDX FETCH FIRST 1 ROWS ONLY;  

To understand this concept practically, let us see some examples using the MySQL database. Consider we have a table items created into the database with the following data:

Table: items

IDItem_NameItem_QuantityItem_PricePurchase_Date
1Soap5200 2021-07-08
2Toothpaste2802021-07-10
3Pen10502021-07-12
4Bottle12502021-07-13
5Brush3902021-07-15

Suppose we want to retrieve any random record from the items table.

We will write the query as follows:

mysql> SELECT * FROM items ORDER BY RAND () LIMIT 1;  

We may get the following results:

IDItem_NameItem_QuantityItem_PricePurchase_Date
3Pen10202021-07-12

Now let us try executing the same query one more time.

mysql> SELECT * FROM items ORDER BY RAND () LIMIT 1;  

We may get the following results:

IDItem_NameItem_QuantityItem_PricePurchase_Date
5Brush3902021-07-15

From the above results, we can conclude that we get different records as output both times even though we executed the same query twice. RAND () function has selected random records both times for the same query from a single table. Therefore, even we execute the same query again, we will get different output every time. There is a rare possibility of getting the same record consecutively using the RAND () function.

Now, suppose you want all the records of the table to be fetched randomly.

To do so, we need to execute the following query:

mysql> SELECT * FROM items ORDER BY RAND ();  

We may get the following results:

IDItem_NameItem_QuantityItem_PricePurchase_Date
4Bottle12502021-07-13
5Brush3902021-07-15
1Soap52002021-07-08
2Toothpaste2802021-07-10
3Pen10502021-07-12

There is also a possibility of getting some different arrangements of records if we execute the RAND () function again on the employees table.


Comments

Leave a Reply

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