SQL ORDER BY RANDOMIf 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.
If you want to return a random row with MY SQL, use the following syntax:
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
Suppose we want to retrieve any random record from the items table. We will write the query as follows: We may get the following results:
Now let us try executing the same query one more time. We may get the following results:
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: We may get the following results:
There is also a possibility of getting some different arrangements of records if we execute the RAND () function again on the employees table. Next TopicSQL ORDER BY LIMIT |