BigQuery’s LEFT JOIN UNNEST keeps orders with no items. COUNT(*) can make them look nonempty.
Keeping every order and counting actual line items are two different jobs. A three-row test exposes the difference in generated GoogleSQL.
A request like “show every order and its line-item count” asks for two things: keep all the orders, and count only the items. In BigQuery, changing an inner UNNEST join to a left join fixes the first problem, but not the second. A generated query that leaves COUNT(*) in place can give an order with no items a count of one.
Why the zero becomes a one
Google’s array guide says flattening with an inner join excludes rows whose arrays are empty or NULL. Use a left join when those rows belong in the report. The GoogleSQL join reference explains what happens next: when the right side supplies no matching row, the join creates a row with NULL values on that side. The order survives, but that row does not represent an item.
The COUNT reference distinguishes COUNT(*), which counts rows, from COUNT(expression), which counts non-NULL expression values. In the example below, sku is the array element and every real element in the fixture is non-NULL. That makes it suitable for the second count.
WITH orders AS (
SELECT 1 AS order_id, ['A', 'B'] AS skus UNION ALL
SELECT 2, ARRAY<STRING>[] UNION ALL
SELECT 3, CAST(NULL AS ARRAY<STRING>)
)
SELECT order_id, COUNT(*) AS joined_rows, COUNT(sku) AS item_count
FROM orders
LEFT JOIN UNNEST(skus) AS sku ON TRUE
GROUP BY order_id
ORDER BY order_id;
The documented rules imply joined_rows of 2, 1, and 1, but item_count of 2, 0, and 0. Those are expected values for this fixture, not results from a live warehouse run. If the business question treats a missing array as unknown rather than empty, specify that separately; this item count deliberately gives both cases zero.
What to test in generated SQL
Assert both the returned order IDs and the per-order counts. Testing only the total can hide a dropped order; testing only that every order appears can miss the phantom item. For arrays of structs, don’t blindly substitute a nullable business field for sku: COUNT(item.some_field) answers how many joined items have that field populated, which can differ from how many items exist. Choose the counted expression to match the question, then add a case where a real item has a missing field.
sources
- Google Cloud: Work with arrays — flattening arraysdocs.cloud.google.com
- GoogleSQL query syntax: Correlated join operationdocs.cloud.google.com
- GoogleSQL aggregate functions: COUNTdocs.cloud.google.com
comments · 0