All for Joomla All for Webmasters

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 a question occurs that what is the need of fetching 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 queries which are altered according to the databases.

Select a random row with MySQL:

If you want to return a random row with MY SQL, Use the following code:

  1. SELECT column FROM table
  2. ORDER BY RAND ()
  3. LIMIT 1

Select a random row with Postgre SQL:

  1. SELECT column FROM table
  2. ORDER BY RANDOM ()
  3. LIMIT 1

Select a random row with SQL Server:

  1. SELECT TOP 1 column FROM table
  2. ORDER BY NEWID ()

Select a random row with oracle:

  1. SELECT column FROM
  2. (SELECT column FROM table
  3. ORDER BY dbms_random.value)
  4. WHERE rownum = 1

Select a random row with IBM DB2:

  1. SELECT column RAND () as IDX
  2. FROM table
  3. ORDER BY  IDX FETCH FIRST 1 ROWS ONLY
PinIt
submit to reddit

Leave a Reply

Top