parsed.org

Tips by tag: random

Random Rows from SQL by http://www.tylermac.net/ on Mar 10, 2007 02:36 PM

It is sometimes useful when working with SQL to grab random rowsets, for debugging stored procedures or simply grabbing a random ad for an ad rotator. Either way, different databases use different functions to select this randomization.

  • Select a random row with MySQL:

    SELECT * FROM mytable
    ORDER BY RAND()
    LIMIT 1;
    
  • Select a random row with PostgreSQL:

    SELECT * FROM mytable
    ORDER BY RANDOM()
    LIMIT 1;
    
  • Select a random row with Microsoft SQL Server:

    SELECT TOP 1 column FROM table
    ORDER BY NEWID();
    
generatormssqlmysqlpostgresqlrandomsql
Select a Random Row by xinu on Jan 12, 2005 10:22 AM

Select a random row from a table with the following query:

SELECT * FROM table ORDER BY random() LIMIT 1;
obscurepostgresqlrandomsql
RSS