parsed.org

Tips by tag: mssql

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
RSS