Using this page as a guide: https://docs.snowflake.com/en/sql-reference/constructs/sample.html
For this exercise, I need to split a portion of the records in a table 50/50:
These work. I get almost exactly 50% of the table row count:
SELECT * FROM MyTable SAMPLE (50);
SELECT * FROM MyTable TABLESAMPLE (50);
As soon as I apply a WHERE clause, SAMPLE no longer works:
SELECT * FROM MyTable
WHERE country = ‘USA’
AND load_date = CURRENT_DATE
SAMPLE (50);
This led me to this from the above snowflake page:
Method 1; applies sample to one of the joined tables
select i, j
from table1 as t1 inner join table2 as t2 sample (50)
where t2.j = t1.i
;
Method 2; applies sample to the result of the joined tables
select *
from (
select *
from t1 join t2
on t1.a = t2.c
) sample (50);
Both methods work but the number of returned records is 57%, not 50% in both cases.
Is QUALIFY ROW_NUMBER() OVER (ORDER BY RANDOM()) a better option? While this does work with a WHERE clause, I can’t figure out how to set a percentage instead of a row count max. Example:
SELECT * FROM MyTable
WHERE country = ‘USA’
AND load_date = CURRENT_DATE
QUALIFY ROW_NUMBER() OVER (ORDER BY RANDOM()) = (50)
--this gives me 50 rows, not 50% of rows or 4,457 rows (total rows after where clause in this example is 8,914)