Aggregates
Aggregate
count()
Returns the number of non-NULL values in arg.
Reference: Haybarn WASM 2.0.0-rc12
Arguments & returns
2 overloadscount()
Aggregate
| Overload link | Returns |
|---|---|
| #01 | BIGINT |
count(arg)
Aggregate
| Overload link | arg |
Returns |
|---|---|---|
| #02 | ANY |
BIGINT |
Count rows and non-null values
Count all rows with count(*) or count only non-null values with count(expression). Add DISTINCT to count distinct non-null values.
Unlike most aggregates, count returns zero on an empty input. NULL values are excluded from count(expression).
Haybarn WASM 2.0.0-rc12 · In your browser
Guide example · Run to view results.
| rows | non_null | distinct_values |
|---|---|---|
3 | 2 | 1 |
Watch for: After a LEFT JOIN, count(*) includes the preserved unmatched row. Count a non-null key from the joined table to count matches.
Example
Haybarn WASM 2.0.0-rc12 · In your browser
Engine example with sample data · Run to view results.
In other engines
Apache Sparkcount()
WITH tbl AS (SELECT 1 AS id, 'eggy' AS name UNION ALL SELECT NULL AS id, 'jake' AS name) SELECT COUNT(DISTINCT id, name) AS cnt FROM tbl
WITH tbl AS (SELECT 1 AS id, 'eggy' AS name UNION ALL SELECT NULL AS id, 'jake' AS name) SELECT COUNT(DISTINCT CASE WHEN id IS NULL THEN NULL WHEN name IS NULL THEN NULL ELSE (id, name) END) AS cnt FROM tbl
Used in larger rewrites 1
These examples use count as one part of a larger SQL translation.
Snowflakeapproximate_similarity()
APPROXIMATE_SIMILARITY(sig_col)
(SELECT CAST(SUM(CASE WHEN num_distinct = 1 THEN 1 ELSE 0 END) AS DOUBLE) / COUNT(*) FROM (SELECT pos, COUNT(DISTINCT h) AS num_distinct FROM (SELECT h, pos FROM UNNEST(LIST(sig_col)) AS _(sig) JOIN UNNEST(CAST(sig -> '$.state' AS UBIGINT[])) WITH ORDINALITY AS s(h, pos) ON TRUE) GROUP BY pos))