In this post we are going to cover the approximate aggregates in Snowflake: APPROX_COUNT_DISTINCT, HLL, APPROX_PERCENTILE and APPROX_TOP_K.
An approximate aggregate gives you an estimate instead of an exact answer. It does that by keeping a small summary of what it has seen rather than the values themselves. The idea is to trade a little accuracy for a cheaper query on a very large table.
We will run each one next to its exact partner, so you can see the syntax and the shape of what comes back. One thing has to be said before we start. These functions exist for tables with billions of rows in them, and the table on this page has forty-one. Every approximate function below returned exactly the right answer on it, every time. That is a real captured result, and it also tells you nothing about the only thing that actually matters, which is what these functions do when the data is big. So read this page for the syntax and the shapes, and take that as the whole of what it offers. There is no accuracy figure here and no speed figure, because neither was measured, and a number invented to fill the gap would be worse than no number at all.
Every query below was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 22 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's start with the exact count next to the approximate one
- Now let's call HLL directly
- Now let's try it on a column with a NULL in it
- Now let's do the same thing with a percentile
- Now let's put both versions side by side, per group
- Now let's ask for the commonest values with APPROX_TOP_K
- So should we use these?
Let's create some sample data
Most of this page works on a table called ORDERS. It is part of the same shared sample-data script that created EMPLOYEES back in episode 1.
Copy this into a Snowflake worksheet and run it once. Then you can run every query on this page yourself.
-- Creates the ORDERS table that Level 2 works on.
-- Part of the shared sample-data script; run it once.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
CREATE OR REPLACE TABLE ORDERS (
ORDER_ID INT,
CUSTOMER_ID INT,
ORDER_DATE DATE,
SHIP_DATE DATE,
STATUS VARCHAR,
AMOUNT NUMBER(10,2),
QUANTITY INT
);
INSERT INTO ORDERS VALUES
(1001, 101, '2023-01-12', '2023-01-15', 'SHIPPED', 4200.00, 12),
(1002, 102, '2023-01-28', '2023-02-02', 'SHIPPED', 890.50, 3),
(1003, 101, '2023-02-14', '2023-02-16', 'SHIPPED', 6150.00, 20),
(1004, 103, '2023-02-27', NULL, 'CANCELLED', 1500.00, 5),
(1005, 104, '2023-03-09', '2023-03-14', 'SHIPPED', 2310.75, 8),
(1006, 101, '2023-03-22', '2023-03-24', 'SHIPPED', 5020.00, 16),
(1007, 105, '2023-04-05', '2023-04-11', 'SHIPPED', 7890.00, 25),
(1008, 102, '2023-04-19', '2023-04-23', 'SHIPPED', 1120.00, 4),
(1009, 103, '2023-05-02', '2023-05-06', 'SHIPPED', 3340.25, 11),
(1010, 106, '2023-05-21', NULL, 'PENDING', 640.00, 2),
(1011, 101, '2023-06-08', '2023-06-10', 'SHIPPED', 8100.00, 27),
(1012, 104, '2023-06-25', '2023-06-30', 'SHIPPED', 1975.50, 7),
(1013, 105, '2023-07-11', '2023-07-15', 'SHIPPED', 6420.00, 21),
(1014, 102, '2023-07-29', '2023-08-03', 'RETURNED', 750.00, 3),
(1015, 107, '2023-08-14', '2023-08-17', 'SHIPPED', 9250.00, 30),
(1016, 103, '2023-08-30', '2023-09-04', 'SHIPPED', 2860.00, 9),
(1017, 101, '2023-09-16', '2023-09-19', 'SHIPPED', 5540.00, 18),
(1018, 106, '2023-10-03', '2023-10-08', 'SHIPPED', 1430.00, 5),
(1019, 105, '2023-10-22', '2023-10-26', 'SHIPPED', 7015.00, 23),
(1020, 107, '2023-11-07', '2023-11-10', 'SHIPPED', 10400.00, 34),
(1021, 102, '2023-11-24', '2023-11-29', 'SHIPPED', 980.00, 4),
(1022, 104, '2023-12-09', NULL, 'CANCELLED', 2250.00, 8),
(1023, 101, '2023-12-27', '2023-12-30', 'SHIPPED', 6730.00, 22),
(1024, 103, '2024-01-15', '2024-01-18', 'SHIPPED', 3910.00, 13),
(1025, 107, '2024-01-31', '2024-02-05', 'SHIPPED', 11200.00, 36),
(1026, 105, '2024-02-17', '2024-02-21', 'SHIPPED', 8340.00, 27),
(1027, 106, '2024-03-04', '2024-03-09', 'SHIPPED', 1690.00, 6),
(1028, 102, '2024-03-21', '2024-03-25', 'SHIPPED', 1240.00, 5),
(1029, 101, '2024-04-06', '2024-04-09', 'SHIPPED', 7460.00, 24),
(1030, 109, '2024-04-23', '2024-04-28', 'SHIPPED', 5180.00, 17),
(1031, 103, '2024-05-10', '2024-05-14', 'SHIPPED', 4025.00, 14),
(1032, 107, '2024-05-28', '2024-06-01', 'SHIPPED', 12850.00, 41),
(1033, 105, '2024-06-13', NULL, 'PENDING', 6900.00, 22),
(1034, 109, '2024-06-30', '2024-07-04', 'SHIPPED', 4760.00, 16),
(1035, 101, '2024-07-18', '2024-07-21', 'SHIPPED', 8820.00, 29),
(1036, 104, '2024-08-02', '2024-08-07', 'SHIPPED', 2540.00, 9),
(1037, 107, '2024-08-25', '2024-08-29', 'SHIPPED', 13100.00, 43),
(1038, 109, '2024-09-11', '2024-09-15', 'SHIPPED', 5930.00, 19),
(1039, 102, '2024-09-29', '2024-10-03', 'RETURNED', 1080.00, 4),
(1040, 101, '2024-10-16', '2024-10-19', 'SHIPPED', 9640.00, 31);
-- One deliberate NULL amount, inserted separately so it is easy to see why it
-- is there: it exists so that COUNT(*), COUNT(AMOUNT) and SUM() give
-- different answers.
INSERT INTO ORDERS VALUES
(1041, 106, '2024-11-05', NULL, 'PENDING', NULL, 3);Count the rows in that script if you like: forty in the first INSERT and one more after it. That one more has NULL in AMOUNT, which matters later in the series and does not change anything here.
Most of the functions below work on three of those columns: CUSTOMER_ID, AMOUNT and STATUS.
Let's start with the exact count next to the approximate one
Counting distinct values exactly means remembering every value we have already seen. That is the only way to tell whether the next one is new. On a small table it costs nothing. On a very large one it is a structure that has to be held in memory and shuffled between compute nodes, and it grows with the number of distinct values.
The approximate version keeps a small fixed-size sketch of what it has seen instead of the values themselves, and estimates the answer from the sketch. That is what HyperLogLog refers to, and HLL is its short name. It is also what APPROX_COUNT_DISTINCT uses underneath.
Let's ask for both counts on the same column, in one query.
SELECT COUNT(DISTINCT CUSTOMER_ID) AS EXACT_DISTINCT, APPROX_COUNT_DISTINCT(CUSTOMER_ID) AS APPROX_DISTINCT FROM ORDERS;| EXACT_DISTINCT | APPROX_DISTINCT |
|---|---|
| 8 | 8 |
EXACT_DISTINCT and APPROX_DISTINCT both came back 8. They are identical, and that is the problem with demonstrating this here rather than a success. There is nothing to approximate. The sketch is small enough to hold this much data exactly, so the estimate is the answer.
Read the rest of this page knowing that. Each pair below agrees, and each agreement is a fact about forty-one rows — not a measurement of how close these functions stay on data where they have something to do. Do not carry “they matched here” forward as “they match”.
Now let's call HLL directly
APPROX_COUNT_DISTINCT is a readable name for the thing. HLL asks for the same estimate by its algorithm's name. The two are interchangeable in a SELECT list.
Let's run it on the same column.
SELECT HLL(CUSTOMER_ID) AS HLL_ESTIMATE FROM ORDERS;| HLL_ESTIMATE |
|---|
| 8 |
8 again, from the same column.
The reason HLL exists under its own name is the family around it. The sketch can be built, stored and combined as a value in its own right, so a nightly job can keep one sketch per day and a dashboard can merge a month of them without re-reading the rows. That family is not captured on this page, so this page does not demonstrate it.
Now let's try it on a column with a NULL in it
Same function, a different column, and a different table. DEPT_ID on EMPLOYEES contains a NULL, and this is where that becomes interesting.
SELECT HLL(DEPT_ID) AS HLL_DEPTS, COUNT(DISTINCT DEPT_ID) AS EXACT_DEPTS FROM EMPLOYEES;| HLL_DEPTS | EXACT_DEPTS |
|---|---|
| 3 | 3 |
HLL_DEPTS is 3 and EXACT_DEPTS is 3. The two agree with each other. And both of them disagree with something we have already seen.
Back in episode 9, SELECT DISTINCT DEPT_ID on this table returned four rows, because NULL was one of them. DISTINCT treats the absence of a department as a department. These two functions do not.
| Episode | Function | What it does with NULL |
|---|---|---|
| 13 | COUNT(DISTINCT ...) | Leaves it out |
| 19 | LISTAGG | Leaves it out |
| 20 | ARRAY_AGG | Leaves it out |
| 22 | HLL / APPROX_COUNT_DISTINCT | Leaves it out |
That is the fourth time for the same rule. Aggregates leave NULLs out, and the approximate ones are no exception. If we want the missing value counted as a category, that is our job to arrange. No function in this family will do it for us.
Now let's do the same thing with a percentile
Cardinality is not the only thing with an approximate version. Percentiles have one too. The obvious thing to put beside it is the exact median from episode 21.
SELECT APPROX_PERCENTILE(AMOUNT, 0.5) AS APPROX_P50, MEDIAN(AMOUNT) AS EXACT_MEDIAN FROM ORDERS;| APPROX_P50 | EXACT_MEDIAN |
|---|---|
| 4890.0 | 4890.00000 |
APPROX_P50 came back 4890.0 and EXACT_MEDIAN came back 4890.00000. The same point on the distribution, once more, on this table.
Those two cells are printed differently because the two functions return different types. APPROX_PERCENTILE returns a floating-point number, and MEDIAN returns a fixed-point one with the scale it inherits from the column. Worth knowing before you compare one against the other in a test, or write either into a typed column.
Have a look at the argument order too. APPROX_PERCENTILE(AMOUNT, 0.5) takes the column and then the fraction as ordinary arguments. It does not use the WITHIN GROUP (ORDER BY ...) form that PERCENTILE_CONT and PERCENTILE_DISC require.
Now let's put both versions side by side, per group
This is the most direct comparison on the page, and the one worth re-running on your own data. Both versions of the same count, for every status, in one result.
SELECT STATUS, APPROX_COUNT_DISTINCT(CUSTOMER_ID) AS APPROX_CUSTOMERS, COUNT(DISTINCT CUSTOMER_ID) AS EXACT_CUSTOMERS
FROM ORDERS GROUP BY STATUS ORDER BY STATUS;| STATUS | APPROX_CUSTOMERS | EXACT_CUSTOMERS |
|---|---|---|
| CANCELLED | 2 | 2 |
| PENDING | 2 | 2 |
| RETURNED | 1 | 1 |
| SHIPPED | 8 | 8 |
Four groups, and in every one of them the two columns hold the same value. On a table of any real size this is the query that would start to show a difference. It would also show you how big that difference is on the data you actually care about, which is worth considerably more than any figure a tutorial could quote you.
One thing to read off that grid carefully: the per-status counts do not add up to the whole-table count of 8 from earlier, and they are not supposed to. A customer who has both a shipped order and a cancelled one is distinct in each group. Distinct counts never sum. That is true of the exact function as well, and it is the reason both columns here had to be computed per group rather than totalled afterwards.
Now let's ask for the commonest values with APPROX_TOP_K
The last one returns something that does not look like the others. Give APPROX_TOP_K a column and a count, and it gives back the most common values as a single nested array, in one cell.
SELECT APPROX_TOP_K(STATUS, 3) AS TOP_STATUSES FROM ORDERS;| TOP_STATUSES |
|---|
| [ [ "SHIPPED", 34 ], [ "PENDING", 3 ], [ "RETURNED", 2 ] ] |
Each inner array is a value and how many times it occurred. SHIPPED with 34, then PENDING, then RETURNED. That shape is genuinely useful rather than awkward. It is one cell we can hand to an application, store in a VARIANT column, or index into, exactly like the arrays in episode 20.
Now look at the third entry
RETURNED is listed with a count of 2. Count the CANCELLED rows in the setup script at the top of this page and you will find it has the same count. That is a tie for third place, and the function returned RETURNED.
How APPROX_TOP_K resolves a tie was not tested here, so this page is not going to tell you that it prefers one value over the other, or that the choice is stable between runs. If third place matters to your answer and your data can tie, check it on your own data before you rely on it.
Which is a good place to say the obvious thing about the K. We asked for three, so we got three. The fourth status exists and is simply not in the result. APPROX_TOP_K answers “what are the commonest few”, never “how many kinds are there”.
So should we use these?
Nothing above helps us choose, so here is the part that does. It is a judgement about consequences, not a number.
| Use the approximate one when | Use the exact one when |
|---|---|
| You are counting distinct values across a very large table | The number ends up on an invoice, a compliance report, or anywhere somebody will reconcile it against another system |
| The answer feeds a dashboard where being slightly off changes no decision anybody makes | Two people could compare their copy of the number and disagree about which is right |
| You have measured the difference on your own data and are happy with it | You have not measured it and the answer is being quoted as fact |
The right-hand column is not an argument that the approximation is bad. It is an argument about cost. Explaining a small discrepancy to an auditor costs more than the query ever saved.
What this page refuses to tell you
- How much faster these are. Nothing here was timed, so there is no figure to give.
- How accurate they are. The documentation publishes an accuracy figure for these functions. Read it for your version of Snowflake rather than taking a number from a tutorial — that is exactly the kind of detail that changes between releases.
- How ties are broken in
APPROX_TOP_K. Not tested here.
And if it matters to you, measure it yourself, on your own data, on a table that is actually big. The per-group query further up this page is the one to start with. It puts the approximate and the exact answer in the same row, so the difference is the thing you read rather than the thing you estimate.
Key points
- The approximate aggregates keep a small fixed-size sketch of what they have seen instead of the values themselves, and estimate the answer from it.
APPROX_COUNT_DISTINCTandHLLask for the same estimate;HLLis named after the HyperLogLog algorithm that produces it.- On this course's sample data every approximate function returned the exact answer. That is a fact about forty-one rows, not a measurement of accuracy.
HLLdropsNULLs, the same asCOUNT(DISTINCT),LISTAGGandARRAY_AGGbefore it. Aggregates leaveNULLs out.APPROX_PERCENTILE(column, fraction)takes ordinary arguments — noWITHIN GROUP (ORDER BY ...).APPROX_TOP_Kreturns a nested array in a single cell: each entry is a value and its count.- Distinct counts do not sum across groups, approximate or exact, so they have to be computed per group.
- Use the approximate version where being slightly off changes no decision. Use the exact one anywhere the number will be reconciled against another system.
- No speed figure and no error figure appear on this page, because neither was measured here. The documentation publishes an accuracy figure; read it for your own version.
Episode 23 — QUALIFY. The clause that filters on the result of a window function the way HAVING filters groups — the third member of a family this level has been building, and the end of Level 2.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the script above. The ORDERS and EMPLOYEES data is invented demo data created by that script. No accuracy, error-bound, performance or benchmark figure is claimed anywhere on this page or anywhere in this series — where a captured approximate value equals the exact one, that is reported as the output of one run on forty-one rows and nothing more. Function behaviour follows the Snowflake cardinality-estimation documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.