Select top random rows ?

  • I need to get a sample random rows from a table. Top will get only first records, but I need my sample to be evenly distributed. The table does not have a surrogate key, instead it has PK that consists of 4 columns. Any ideas ?

    Thanks

  • Mark Shvarts (12/18/2008)


    I need to get a sample random rows from a table. Top will get only first records, but I need my sample to be evenly distributed. The table does not have a surrogate key, instead it has PK that consists of 4 columns. Any ideas ?

    Thanks

    SELECT TOP 10 *

    FROM MyTable

    ORDER BY NEWID()

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden

  • NEWID is the quickest way I know too

    Can look into TABLESAMPLE as well

    http://msdn.microsoft.com/en-us/library/ms189108(SQL.90).aspx

    SELECT FirstName, LastName

    FROM Person.Contact

    TABLESAMPLE (10 PERCENT) ;

    You can use TABLESAMPLE to quickly return a sample from a large table when either of the following conditions is true:

    * The sample does not have to be a truly random sample at the level of individual rows.

    * Rows on individual pages of the table are not correlated with other rows on the same page.

    SQLServerNewbieMCITP: Database Administrator SQL Server 2005

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply