Sampling Queries

Description

The TABLESAMPLE statement is used to sample the table. It supports the following sampling methods:

  • TABLESAMPLE(x ROWS): Sample the table down to the given number of rows.
  • TABLESAMPLE(x PERCENT): Sample the table down to the given percentage. Note that percentages are defined as a number between 0 and 100.
  • TABLESAMPLE(BUCKET x OUT OF y): Sample the table down to a x out of y fraction.

Note: TABLESAMPLE returns the approximate number of rows or fraction requested.

Syntax

  1. TABLESAMPLE ({ integer_expression | decimal_expression } PERCENT)
  2. | TABLESAMPLE ( integer_expression ROWS )
  3. | TABLESAMPLE ( BUCKET integer_expression OUT OF integer_expression )

Examples

  1. SELECT * FROM test;
  2. +--+----+
  3. |id|name|
  4. +--+----+
  5. | 5|Alex|
  6. | 8|Lucy|
  7. | 2|Mary|
  8. | 4|Fred|
  9. | 1|Lisa|
  10. | 9|Eric|
  11. |10|Adam|
  12. | 6|Mark|
  13. | 7|Lily|
  14. | 3|Evan|
  15. +--+----+
  16. SELECT * FROM test TABLESAMPLE (50 PERCENT);
  17. +--+----+
  18. |id|name|
  19. +--+----+
  20. | 5|Alex|
  21. | 2|Mary|
  22. | 4|Fred|
  23. | 9|Eric|
  24. |10|Adam|
  25. | 3|Evan|
  26. +--+----+
  27. SELECT * FROM test TABLESAMPLE (5 ROWS);
  28. +--+----+
  29. |id|name|
  30. +--+----+
  31. | 5|Alex|
  32. | 8|Lucy|
  33. | 2|Mary|
  34. | 4|Fred|
  35. | 1|Lisa|
  36. +--+----+
  37. SELECT * FROM test TABLESAMPLE (BUCKET 4 OUT OF 10);
  38. +--+----+
  39. |id|name|
  40. +--+----+
  41. | 8|Lucy|
  42. | 2|Mary|
  43. | 9|Eric|
  44. | 6|Mark|
  45. +--+----+