Explain TABLESAMPLE and other approaches to random sampling in SQL. When and why would you sample, and what are the trade-offs?
Last updated
TABLESAMPLEreturns a random subset fast:BERNOULLIsamples individual rows fairly but scans everything, whileSYSTEMsamples whole pages (faster but biased if data is ordered on disk).REPEATABLE(seed)makes it reproducible.Alternatives:
ORDER BY RANDOM() LIMIT ngives exact n rows but sorts the whole table. A hash filter likeMOD(HASH(id), 100) = 0gives a stable sample across runs and joins.Sample for quick exploration, approximate aggregates, or dev datasets. Accept sampling error and scale counts by the sampling fraction.