Selecting a Random Row from a Database Table

Selecting a Random Row from a Database Table

Here are a few ways to select a random row from a database table. These SQL statements won't require any additional application logic to pull the information you need.

Select a random row with MySQL:

SELECT column FROM table ORDER BY RAND() LIMIT 1

Select a random row with PostgreSQL:

SELECT column FROM table ORDER BY RANDOM() LIMIT 1

Select a random row with Microsoft SQL Server:

SELECT TOP 1 column FROM table ORDER BY NEWID()

Select a random row with IBM DB2:

SELECT column FROM table ORDER BY RAND() FETCH FIRST 1 ROWS ONLY

Select a random record with Oracle:

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

Return to Main Page

Comments

Add Comment




On This Site

  • About this site
  • Main Page
  • Most Recent Comments
  • Complete Article List
  • Sponsors

Search This Site


Syndicate this blog site

Powered by BlogEasy


Free Blog Hosting