What is TABLESAMPLE?
It is a clause used in the SQL SELECT statement to retrieve the random number of data from a table without any specific order. There are three ways to achieve this,
- By Percentage
- By No of rows
- By Seed number
By Percentage
TABLESAMPLE percentage will return the percentage of the data pages of a table. Let's look into an example of the AdventureWorks2019 database with the customer table of 19,820 rows.
SELECT *FROM Sales.Customer TABLESAMPLE(10 PERCENT);You may assume that TABLESAMPLE will return the 10 percentage of total rows which is 19,820 but it doesn't. It will return the percentage of data pages not total number of rows. Let's look into an below example,
Example 1:
Example 2:
As you can see in the above examples, when we executed the query in the first example returned 3,135 rows and the second example returned 2,475 rows. TABLESAMPLE will return the percentage of data pages not the percentage of total rows of a table.
By No of rows
SELECT *FROM Sales.Customer TABLESAMPLE(100 ROWS);TABLESAMPLE ROWS doesn't return the actual number of rows from a table. Basically, it converts the number of rows into percentages and returns the results from data pages accordingly.
By Seed number
With REPEATABLE we can get the same results every time by using the seed parameter.
SELECT *FROM [Production].[ProductInventory] TABLESAMPLE(10 PERCENT) REPEATABLE(170);
Where can we use it?
It can be used when there is no need to retrieve the entire table data and without specific ordering like asc / desc.
Example: Blog home page with 2 percentage of the random article in any order
Comments