Wednesday, December 15, 2010

Get sample data from a SQL table

In TSQL, the TABLESAMPLE clause limits the number of rows returned from a table in the FROM clause to a sample number or PERCENT of rows. For example:

/*Return a sample 10 percent of the rows of the result set. */
TABLESAMPLE (10 PERCENT)
/* Return a sample of 15 rows from the result set. */.
TABLESAMPLE (15 ROWS

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.
TABLESAMPLE cannot be applied to derived tables, tables from linked servers, and tables derived from table-valued functions, rowset functions, or OPENXML. TABLESAMPLE cannot be specified in the definition of a view or an inline table-valued function.

Example:

Use AdventureWorks2008
GO

select *
from Sales.Customer
tablesample( 2 percent);
--REPEATABLE (205)


No comments:

Post a Comment