SQL traps every data engineer must know: why your query returns the wrong number without any error
TL;DR
Difficulty: Intermediate
A query that fails is easy. The dangerous one runs and returns a wrong number.
- Most silent errors are grain mismatches: joins that multiply rows, GROUP BY that splits them, averages that weigh them wrongly, filters that drop them.
- Aggregate child tables to the parent's grain before you join, and count rows after every join.
- Never NOT IN with a subquery (one NULL returns nothing), use NOT EXISTS. Use half open date ranges, not BETWEEN.
- Store numerators and denominators, never average the averages. Watch integer division and floats for money.
- Convert time with named zones: Rails stores UTC without saying so.
- Pin every important number to a trusted total with a test.
The query ran, the dashboard looks tidy, and the revenue is almost three times what the shop actually took. No error, no warning. This chapter walks through the silent errors in SQL one by one, on the order data of an invented homeware shop in Limerick: the broken query, the wrong number it gives, why, and the fix that makes it right and keeps it right.
The query ran, and the number is wrong
A query that fails is a gift. It stops, it shows a red message, and you fix it. The dangerous query is the one that runs, returns a tidy number, and is wrong. Nobody gets an error. The number goes into a report, then into a meeting, then into a decision about stock, staff or advertising.
This chapter is about those silent errors in SQL (Structured Query Language, the language almost every database and warehouse speaks). Each section shows one trap: the broken query, the wrong result it gives on real looking data, why it happens, and the fix. Most of them come down to three habits, so here they are up front:
- Know the grain of every table and every result. The grain is what one row stands for: one order, one order line, one payment attempt, one customer per day. The previous chapter on grain, keys, facts and dimensions explains it in depth. Almost every trap below is a grain problem in disguise.
- Count rows after every join. If you expect one row per order and get more, something multiplied. If you get fewer, something dropped.
- Test every query against a total you already trust. The order table, the payment provider's settlement file or last month's signed off report. A query that cannot be checked against anything is a guess with good formatting.
The SQL here is PostgreSQL unless I say otherwise, because PostgreSQL is what most Ruby on Rails shops run. Where Google BigQuery behaves differently, and it does in a few places that matter, I say so.
A few terms first, so nobody is left behind:
| Term | What it means |
|---|---|
| Join | Combining rows from two tables where a condition matches, such as an order and its lines |
| Aggregate | A function that turns many rows into one value: SUM, COUNT, AVG, MIN, MAX |
| NULL | The database's marker for "no value here", which is not zero and not an empty text |
| Window function | A calculation across related rows that keeps every row, such as a running total |
| CTE | Common table expression: a named step inside a query, written with WITH |
| Fan out | A join that turns one row into several, so sums over it count things more than once |
Example: the shop and the month in every example
Every example uses Shannonside Home, an invented online homeware shop in Limerick (shannonsidehome.example). Niamh owns it, Callum is the developer and data engineer. The shop runs on Ruby on Rails and Solidus with PostgreSQL, sends GA4 data to BigQuery every day, gets a daily CSV from its third party logistics warehouse (the 3PL), and pulls payment settlement files from Stripe and PayPal.
The month is November 2026, and these are the numbers Callum trusts because they come straight from the order table:
| Fact for November 2026 | Value |
|---|---|
| Completed orders | 1,980 |
Revenue (sum of spree_orders.total, including VAT and shipping) | €166,320 |
| Average order value | €84 |
Order lines (spree_line_items) | 4,260 |
| Sessions (GA4) | 110,000 |
| Products in the catalogue | 1,400 |
All numbers in this chapter are invented for the example. Keep the €166,320 in mind. Several broken queries below will give you a very different figure, and none of them will complain.
Join fan out: the join that doubles your revenue
The most common silent error in analytics is the fan out. You join a table with one row per order to a table with many rows per order, and then sum a column that belonged to the order. Every order's total is now repeated once for every line it has, and the sum counts it again each time.
It happens because SQL does exactly what you ask. A join produces one output row for every matching pair. An order with three lines matches three line rows, so it appears three times. If you then also join payments, and that order had a failed card attempt before the successful one, each of the three rows meets two payment rows and becomes six.
Example: three orders, three different totals
Callum takes three orders from 3 November to see the mechanism with numbers small enough to check by hand. The Solidus tables are spree_orders, spree_line_items and spree_payments, and the columns used here (total, order_id, quantity, price, amount, state) exist in the Solidus schema1.
| Order | Total | Lines | Payment rows |
|---|---|---|---|
| R100 | €84.00 | 2 | 1 (completed) |
| R101 | €98.00 | 3 | 2 (one failed, one completed) |
| R102 | €84.00 | 1 | 1 (completed) |
The true revenue is €84 + €98 + €84 = €266.
The innocent looking query:
-- PostgreSQL: looks fine, is wrong
SELECT SUM(o.total) AS revenue, COUNT(*) AS row_count
FROM spree_orders o
JOIN spree_line_items li ON li.order_id = o.id
JOIN spree_payments p ON p.order_id = o.id;
Result, run on PostgreSQL 18:
| revenue | row_count |
|---|---|
| 840.00 | 9 |
Here is where €840 comes from. R100 appears 2 × 1 = 2 times, so it adds €168. R101 appears 3 × 2 = 6 times, so it adds €588. R102 appears once and adds €84. Then €168 + €588 + €84 = €840. Join only the line items and you get €546 from 6 rows: €168 + €294 + €84.
The general rule behind it
What the fanned query returns is a weighted sum. Each order's total is multiplied by the number of rows it became after the joins:
where is the revenue the broken query reports, is the number of orders, is the total of order , and is the number of rows order turned into after the joins (lines times payment rows). The true revenue is the same sum with every . Because big orders tend to have more lines, the error is not a neat multiple of the true figure: it is the true revenue times a revenue weighted average of . Foundations: the mean explains weighted averages if you want the groundwork.
Example: what the fan out does to all of November
Callum groups November's 1,980 orders by how many lines they have:
| Lines per order | Orders | Revenue of these orders | Rows after the line join | Revenue as the broken query sees it |
|---|---|---|---|---|
| 1 | 760 | €36,480 | 1 each | €36,480 |
| 2 | 590 | €45,430 | 2 each | €90,860 |
| 3 | 380 | €40,660 | 3 each | €121,980 |
| 4 | 160 | €22,080 | 4 each | €88,320 |
| 5 or more (6 on average) | 90 | €21,670 | 6 each | €130,020 |
| Total | 1,980 | €166,320 | €467,660 |
Joined to the line items alone, the query reports €467,660, which is 2.81 times the truth, because .
Then the payments. In November, 132 orders have two payment rows, a failed attempt and a successful one. To keep the arithmetic simple, assume these 132 orders look like the average order: €84 and 2.15 lines. Each of them is counted a second time, which adds
where is the number of orders with two payment rows, their total in euro and their lines. So the query that joins orders, lines and payments reports €467,660 + €23,839.20 = €491,499.20.
The fix: bring every table to the same grain before you join
Aggregate each child table to the order grain first, then join one row to one row. The CTEs below do that:
-- PostgreSQL: one row per order at every step
WITH line_totals AS (
SELECT order_id,
COUNT(*) AS line_count,
SUM(quantity * price) AS item_revenue
FROM spree_line_items
GROUP BY order_id
),
paid AS (
SELECT order_id,
SUM(amount) AS amount_paid
FROM spree_payments
WHERE state = 'completed' -- failed, void and invalid attempts are not money
GROUP BY order_id
)
SELECT COUNT(*) AS orders,
SUM(o.total) AS revenue,
SUM(lt.item_revenue) AS item_revenue,
SUM(p.amount_paid) AS amount_paid
FROM spree_orders o
LEFT JOIN line_totals lt ON lt.order_id = o.id
LEFT JOIN paid p ON p.order_id = o.id
WHERE o.completed_at IS NOT NULL;
On the three test orders this returns 3 orders, €266 revenue, €266 item revenue and €266 paid. The state = 'completed' filter matters too: Solidus payments move through states such as checkout, processing, pending, completed, failed, void and invalid2, and only completed ones are money that arrived.
Two habits make fan out rare. Write the expected grain as a comment at the top of every query ("one row per order"). And check it: SELECT order_id, COUNT(*) FROM result GROUP BY 1 HAVING COUNT(*) > 1 must return nothing.
The same trap in BigQuery: UNNEST on the GA4 export
GA4's BigQuery export stores one row per event, and the purchased products sit inside that row as a repeated field called items. The purchase value sits in ecommerce.purchase_revenue, once per event3. To look at products you write UNNEST(items), which turns one event row into one row per item. Sum the purchase revenue after that and you have built a fan out without a single JOIN keyword in sight.
-- BigQuery: wrong, revenue is repeated once per item in the basket
SELECT SUM(ecommerce.purchase_revenue) AS revenue
FROM `shannonside.analytics_123456.events_*`, UNNEST(items) AS item
WHERE event_name = 'purchase'
AND _TABLE_SUFFIX BETWEEN '20261101' AND '20261130';
-- BigQuery: right, event level revenue from event level rows
SELECT SUM(ecommerce.purchase_revenue) AS revenue
FROM `shannonside.analytics_123456.events_*`
WHERE event_name = 'purchase'
AND _TABLE_SUFFIX BETWEEN '20261101' AND '20261130';
_TABLE_SUFFIX is a text comparison on the daily table names, so BETWEEN is safe here. Further down you will see why it is not safe on time stamps. If you need item revenue, sum item.price * item.quantity from the unnested rows instead, which is a different number on purpose. Why GA4 and the shop never agree exactly, even with a correct query, is the subject of when analytics, ads and orders disagree.
Many to many joins: when every category claims the same sale
A many to many relationship is one where both sides can have several partners. A product can sit in several categories, and a category holds many products. Solidus stores this in the link table spree_products_taxons (a taxon is Solidus's word for a category node)1. Join sales through it and every sale is counted once per category its product belongs to.
Sometimes that is exactly what you want: "how much did products tagged Gifts sell?" is a fair question. The error is adding those category figures together, or showing them as slices of one pie.
Example: the categories add up to more than the shop sold
November's item revenue (lines only, before shipping) is €149,688. Callum's category report:
| Category | Item revenue |
|---|---|
| Kitchen | €53,900 |
| Living room | €44,450 |
| Bedroom | €31,970 |
| Bathroom | €19,368 |
| Gifts | €50,100 |
| Sum of the rows | €199,788 |
Every product in Gifts also sits in one of the four rooms. Kitchen, Living room, Bedroom and Bathroom alone add up to €53,900 + €44,450 + €31,970 + €19,368 = €149,688, the true figure. Gifts is a second view of €50,100 that is already inside those four. Summing all five rows counts it twice: €149,688 + €50,100 = €199,788.
The fix depends on the question:
- Shares that add up to 100%: give every product exactly one primary category. Solidus has no such column, so Callum keeps a small mapping table (a dbt seed) of
product_id, primary_category, and a test that every product appears in it exactly once. - Overlapping views: keep Gifts, but show it as a separate figure with a note, never in the same total or pie as the rooms.
- Splitting a sale across categories: allocate it, for example half to each of two categories, so the weights for each line add up to 1. Say in the report that it is an allocation.
NULL in joins: rows that vanish without a trace
NULL means "unknown". SQL treats any comparison with an unknown as unknown, so NULL = NULL is not true. It is NULL. PostgreSQL's documentation lists the operators that behave differently: IS NULL, and IS DISTINCT FROM, which treats NULL as a comparable value4.
In a join, that means a row whose key is NULL matches nothing. An inner join drops it, silently. No error, just a shorter result.
Example: 48 order lines fall out of the shipping report
The 3PL uses its own SKU (stock keeping unit, the product code) format with a prefix, so Callum maps it to the shop's SKUs in a staging model. For 48 of November's 4,260 order lines, the 3PL rows that shipped them could not be mapped, so their mapped_sku is NULL. The report joins order lines to shipped units on SKU:
-- PostgreSQL: inner join, lines with a NULL key disappear
SELECT COUNT(*) AS lines_matched
FROM stg_order_lines ol
JOIN stg_3pl_shipments s ON s.mapped_sku = ol.sku AND s.order_number = ol.order_number;
It returns 4,212 lines, and nothing tells you that 48 are missing. Two fixes, used together: use a LEFT JOIN and count the unmatched rows explicitly, and test the mapping so that a NULL mapped_sku fails the build before it reaches a report.
-- PostgreSQL: keep every line, and say how many did not match
SELECT COUNT(*) AS lines_total,
COUNT(*) FILTER (WHERE s.mapped_sku IS NULL) AS lines_unmatched
FROM stg_order_lines ol
LEFT JOIN stg_3pl_shipments s
ON s.mapped_sku = ol.sku AND s.order_number = ol.order_number;
Result: 4,260 lines in total, 48 unmatched. Now the gap is a number on the page that someone has to explain. When you genuinely want two NULLs to count as equal, for example on an optional column in a composite key, write a IS NOT DISTINCT FROM b instead of a = b.
NOT IN with a single NULL returns nothing at all
This one deserves its own section because the result is so total. x NOT IN (subquery) returns true only when x is unequal to every value in the list. If the list contains a NULL, then for any x that is not in the list, the comparison with the NULL is unknown, and the whole expression becomes NULL rather than true. PostgreSQL's documentation spells it out: if there are no equal values and at least one NULL, the result of NOT IN is null5. A WHERE clause keeps only rows where the condition is true, so you get no rows. BigQuery follows the same rule6. The PostgreSQL community wiki lists "Don't use NOT IN" among its common mistakes for this reason7.
Example: "every order has shipped"
Niamh wants the list of November orders the 3PL has not yet dispatched. Callum writes:
-- PostgreSQL: returns zero rows as soon as one order_ref is NULL
SELECT o.number
FROM spree_orders o
WHERE o.completed_at >= '2026-11-01' AND o.completed_at < '2026-12-01'
AND o.number NOT IN (SELECT order_ref FROM raw_3pl_shipments);
The 3PL file includes 6 rows for stock transfers and returns to suppliers, which have no order reference, so order_ref is NULL on those rows. The query returns zero rows. The report says every order has shipped. In truth, 39 have not.
You can see the rule in one line:
SELECT 'R1' NOT IN (SELECT x FROM (VALUES ('R2'), (NULL)) v(x)) AS result;
-- result: NULL (shown as empty), not true
The fix is NOT EXISTS, which asks "is there any matching row?" and is not affected by NULLs in the other table:
-- PostgreSQL: correct, returns the 39 open orders
SELECT o.number
FROM spree_orders o
WHERE o.completed_at >= '2026-11-01' AND o.completed_at < '2026-12-01'
AND NOT EXISTS (
SELECT 1 FROM raw_3pl_shipments s WHERE s.order_ref = o.number
);
A LEFT JOIN with WHERE s.order_ref IS NULL does the same job. Either way, make it a rule: never NOT IN with a subquery.
COUNT(*), COUNT(column) and COUNT(DISTINCT) answer different questions
Three ways of counting, three different answers, all correct for their own question:
COUNT(*)counts rows.COUNT(column)counts rows where that column is not NULL8.COUNT(DISTINCT column)counts different non NULL values.
The trap is using one when you mean another, and the trap behind that is believing a distinct count of a column counts real world things.
Example: how many customers bought in November?
Callum runs five counts on November's orders:
-- PostgreSQL
SELECT COUNT(*) AS orders,
COUNT(user_id) AS orders_with_account,
COUNT(DISTINCT user_id) AS accounts,
COUNT(DISTINCT email) AS raw_emails,
COUNT(DISTINCT lower(trim(email))) AS people_by_email
FROM spree_orders
WHERE completed_at >= '2026-11-01' AND completed_at < '2026-12-01';
| orders | orders_with_account | accounts | raw_emails | people_by_email |
|---|---|---|---|---|
| 1,980 | 1,568 | 1,401 | 1,796 | 1,741 |
Reading the table left to right:
- 1,980 orders.
- 412 of them were guest checkouts with no
user_id, soCOUNT(user_id)drops to 1,568. Anyone who wrote that as "customers" has just lost every guest. - 1,401 distinct accounts placed those 1,568 account orders. But an account is not a person: 3.1% of Shannonside's accounts are duplicates, the same person with an email that differs only in capitals or a stray space, or a guest checkout and an account side by side.
- 1,796 distinct email texts, including guests.
- 1,741 distinct emails once lower case and trimmed. 55 "customers" were the same people typed differently.
None of these is "the number of customers". The best of them, 1,741, still counts a person with two different email addresses twice. Resolving people properly is a whole discipline, and a later chapter in this series on duplicates and entity resolution takes it on. For now, the rule: name the column after what it really counts (distinct_emails, not customers).
Aggregates skip NULLs, and SUM of nothing is NULL
Every aggregate except COUNT ignores NULL inputs, and returns NULL, not zero, when it has no rows at all. PostgreSQL's documentation puts it plainly: the sum of no rows returns null, not zero as one might expect8.
Example: the average that forgot the unanswered tickets
Shannonside's customer service tool logged 620 tickets in November. 590 got a first reply, on average after 3.1 hours. 30 had no reply at all, so their first_response_hours is NULL. AVG(first_response_hours) returns 3.1 hours, because it simply ignores the 30. The honest report says: "590 tickets answered, after 3.1 hours on average. 30 unanswered (4.8%)", because 30 / 620 = 4.8%.
Example: the Sunday with no refunds
Callum's daily view computes net revenue as revenue minus refunds, with refunds summed in a subquery. On Sunday 8 November no refund was issued, the refund subquery has no rows, SUM returns NULL, and €4,620 minus NULL is NULL. The day shows a blank. The fix is COALESCE(SUM(r.amount), 0), which turns "no rows" into zero where zero is the truth.
Integer division: the conversion rate of zero
In PostgreSQL, dividing one integer by another throws away the remainder: 5 / 2 is 2, and the documentation says division of integral types truncates towards zero9. Counts are integers. So the first conversion rate anyone computes from a daily KPI table is often exactly zero.
Example: three ways to compute the return rate
In November, 178 of the 1,980 orders had a return. The rate is 178 / 1,980 = 8.99%.
-- PostgreSQL, run on version 18
SELECT 178 / 1980 AS a,
178 * 100 / 1980 AS b,
100.0 * 178 / 1980 AS c,
ROUND(100.0 * 178 / 1980, 1) AS d;
| a | b | c | d |
|---|---|---|---|
| 0 | 8 | 8.9898989898989899 | 9.0 |
Column a is zero: the classic. Column b is worse, because it looks plausible. Multiplying by 100 first gives 17,800 / 1,980, which truncates to 8, so the dashboard says 8% when the truth is 9.0%. Column c starts with a decimal (100.0), so PostgreSQL computes in the exact numeric type. Column d rounds for display. Divide by zero is the other half of the problem: on a day with no sessions, orders / sessions raises an error. orders::numeric / NULLIF(sessions, 0) returns NULL instead, which is honest: the rate is undefined.
BigQuery is different, and this catches people who move queries between engines. There, / on two INT64 values returns a FLOAT64, so 178 / 1980 gives 0.0899 and not 06. Integer division in BigQuery is the DIV function, and SAFE_DIVIDE returns NULL instead of an error on division by zero10. The same query text gives different numbers on the two engines.
Floats: the legacy prices that never quite add up
The second number type trap is floating point. Types such as PostgreSQL's double precision are inexact by design11. They store the nearest binary fraction, and 0.1 has no exact binary form. David Goldberg's classic paper on floating point arithmetic explains why12. Shannonside's import from its old platform stored prices from 2019 to 2021 as floats.
-- PostgreSQL: ten prices of 0.10 as float and as numeric
SELECT SUM(x) AS float_sum,
SUM(x::numeric) AS numeric_sum
FROM (SELECT 0.1::float8 AS x FROM generate_series(1, 10)) s;
| float_sum | numeric_sum |
|---|---|
| 0.9999999999999999 | 1.0 |
Over five years of history, those tiny errors make a reconciliation test of "sum of legacy lines equals the old platform's export total" fail by a penny here and there, and an equality check such as WHERE price = 19.99 miss rows. The fix is to cast floats to numeric(12,2) once, in the staging layer, and never do money arithmetic in floats after that. The chapter on data types, schemas and formats covers money types in depth.
Averages of averages: the conversion rate nobody had
An average of rates is only right when every rate has the same weight. It almost never does. A channel with 4,000 sessions and one with 50,000 sessions should not count equally in the shop's conversion rate, but a plain AVG(conversion_rate) over a channel table gives them equal votes.
The correct overall rate comes from the totals, which is the same as weighting each channel's rate by its share of sessions:
where is the overall conversion rate, runs over the channels, is the number of orders from channel , is its number of sessions, and is channel 's share of all sessions, its weight. See Foundations: ratios and rates and Foundations: the mean for the groundwork.
Example: 2.91% or 1.8%?
Callum's channel table for November:
| Channel | Sessions | Orders | Conversion rate |
|---|---|---|---|
| Organic search | 50,000 | 920 | 1.84% |
| Google Ads | 30,000 | 560 | 1.87% |
| Meta Ads | 26,000 | 216 | 0.83% |
| 4,000 | 284 | 7.10% | |
| Total | 110,000 | 1,980 |
The average of the four rates is (1.84 + 1.87 + 0.83 + 7.10) / 4 = 11.64 / 4 = 2.91%.
The true rate is
where is the total number of orders and the total number of sessions, so the true rate is 1.8%. The average of averages overstates it by more than half, because email, the smallest channel, has by far the highest rate and gets a quarter of the vote. With weights, the email channel's share is 4,000 / 110,000 = 3.6%, and its 7.10% contributes only 0.036 × 7.10 = 0.26 percentage points.
The same trap appears in every rollup: the average of daily average order values is not the month's average order value, and the average of each region's return rate is not the shop's return rate. Store the numerator and the denominator, sum each, divide at the end. Groups can even reverse a comparison when you combine them, which statisticians call Simpson's paradox13. Statistical thinking for growth: why averages mislead you goes further into averages that lie.
GROUP BY at the wrong grain: one customer, two rows
GROUP BY decides the grain of your result. Every column you add to it can split groups further. Add a column that varies within what you think of as one thing, and that thing becomes several rows, each with part of its total.
Example: the top customer who was not on the list
Niamh asks for the top 20 customers by lifetime revenue, with their country. Callum writes:
-- PostgreSQL: grain is (account, country text), not account
SELECT o.user_id, a.country_text, SUM(o.total) AS lifetime_revenue
FROM spree_orders o
JOIN stg_addresses a ON a.id = o.bill_address_id
WHERE o.completed_at IS NOT NULL
GROUP BY o.user_id, a.country_text
ORDER BY lifetime_revenue DESC
LIMIT 20;
Old addresses store country as free text: "Ireland", "IE", "IRL", "Republic of Ireland". Account 4417 has orders under "Ireland" worth €1,450 and under "IRL" worth €1,620. The true lifetime revenue is €1,450 + €1,620 = €3,070, enough for 12th place. Split in two, neither half reaches the top 20, which starts at €1,840. Across all accounts, the query returns 1,448 groups for 1,401 accounts, so 47 accounts are split.
The fix is to group at the grain of the question (user_id), and attach descriptive columns afterwards from a dimension with exactly one row per customer. Standardising the country itself belongs to the cleaning layer, and a later chapter in this series on standardising values works through it. A quick test for any result: COUNT(*) must equal COUNT(DISTINCT user_id).
A WHERE clause that turns a LEFT JOIN into an INNER JOIN
A LEFT JOIN keeps every row of the left table, with NULLs where the right table had no match. Put a condition on the right table into the WHERE clause, and those NULL rows fail it and disappear. Your LEFT JOIN now behaves like an inner join. PostgreSQL's documentation explains why: a restriction in the ON clause is applied before the join, a restriction in WHERE after it, and that matters a lot with outer joins14.
Example: the dead stock report with no dead stock
Niamh wants every product with its November sales, so she can see what did not sell. Shannonside has 1,400 products. 1,212 sold at least once in November, so 188 did not.
-- PostgreSQL: wrong, the date filter in WHERE removes unsold products
SELECT p.id, p.name, COALESCE(SUM(li.quantity), 0) AS units
FROM spree_products p
LEFT JOIN spree_variants v ON v.product_id = p.id
LEFT JOIN spree_line_items li ON li.variant_id = v.id
LEFT JOIN spree_orders o ON o.id = li.order_id
WHERE o.completed_at >= '2026-11-01' AND o.completed_at < '2026-12-01'
GROUP BY p.id, p.name;
It returns 1,212 rows. For the 188 unsold products, o.completed_at is NULL, the comparison is unknown, and WHERE drops them. The report Niamh asked for, the one about products that did not sell, contains not one of them.
The fix is to aggregate sales first and join the result to the product list:
-- PostgreSQL: right, 1,400 rows, 188 of them with 0 units
WITH november_units AS (
SELECT v.product_id, SUM(li.quantity) AS units
FROM spree_line_items li
JOIN spree_orders o ON o.id = li.order_id
JOIN spree_variants v ON v.id = li.variant_id
WHERE o.completed_at >= '2026-11-01' AND o.completed_at < '2026-12-01'
GROUP BY v.product_id
)
SELECT p.id, p.name, COALESCE(nu.units, 0) AS units
FROM spree_products p
LEFT JOIN november_units nu ON nu.product_id = p.id;
Moving the date conditions into the ON clause of the orders join also keeps all products, but then line items from other months still join through to the variants. Aggregating first is clearer and leaves nothing to reason about.
Time zones: the order that happened yesterday
Time is where good queries quietly go wrong, because the same moment has different dates in different places. The order at 12.20am in Limerick on 1 June 2026 happened at 11.20pm on 31 May in UTC (Coordinated Universal Time). Irish law sets standard time at one hour ahead of Greenwich Mean Time, with a period of winter time on GMT itself, so outside winter time Irish clocks run an hour ahead of UTC15.
Three facts about Shannonside's data make this real:
- The shop stores UTC, in a column without a time zone. Rails reads and writes times in UTC by default16, and on PostgreSQL its
datetimecolumns usetimestamp without time zoneunless you configure otherwise17. Socompleted_atholds UTC, but nothing in the column says so. - The 3PL sends local time without a zone. Its file says
2026-07-02 16:10, meaning Limerick time. - GA4 uses both. In the BigQuery export,
event_dateis the date in the property's time zone, whileevent_timestampis in microseconds, UTC3.
Example: May steals June's first hour
Callum's monthly revenue query truncates completed_at to the month:
-- PostgreSQL: months in UTC, not in Irish time
SELECT date_trunc('month', completed_at) AS month, SUM(total)
FROM spree_orders WHERE completed_at IS NOT NULL GROUP BY 1;
Eleven orders worth €924 were placed between midnight and 1am on 1 June, Irish time. In UTC they are 31 May, so the report books them in May. The same happens to the first hour of every day all summer, which moves the launch hour of a midnight sale to the day before.
The correct conversion for a UTC value stored without a zone takes two steps, and PostgreSQL's documentation describes both directions of AT TIME ZONE18. Here is the query:
-- PostgreSQL: say it is UTC, then show it in Irish time
SELECT date_trunc('month',
(completed_at AT TIME ZONE 'UTC') AT TIME ZONE 'Europe/Dublin'
) AS month_london,
SUM(total) AS revenue
FROM spree_orders
WHERE completed_at IS NOT NULL
GROUP BY 1;
The first AT TIME ZONE 'UTC' turns the bare value into an absolute moment (a timestamp with time zone). The second shows that moment as Irish wall clock time. On the example value, timestamp '2026-05-31 23:20:00' AT TIME ZONE 'UTC' AT TIME ZONE 'Europe/Dublin' returns 2026-06-01 00:20:00, so the order moves into June where it belongs. Always use a named zone such as Europe/Dublin, never a fixed offset like +01, so the summer time rules apply on the right dates.
Note the trap that hides this bug: in November Ireland is on winter time, which is GMT and matches UTC, so every test Callum runs in winter passes. The bug only shows once the clocks go forward in spring.
Example: the dispatch time that gained an hour
Shannonside promises same day dispatch for orders before 2pm. Callum measures it by subtracting completed_at from the 3PL's shipped_at. An order placed at 1.30pm on 2 July (stored as 12:30 UTC) was shipped at 4.10pm Limerick time (the file says 16:10). The naive difference, 16:10 minus 12:30, is 3 hours 40 minutes. The true answer is 2 hours 40 minutes. Worse, the cut off check completed_at::time < '14:00' compares a UTC time with a Limerick rule, so an order at 2.20pm Limerick time (13:20 UTC) counts as "before 2pm" and becomes a false missed promise.
The fix converts both sides to absolute moments before any arithmetic:
-- PostgreSQL: both sides as timestamptz
SELECT s.shipped_at_local AT TIME ZONE 'Europe/Dublin' AS shipped_at,
o.completed_at AT TIME ZONE 'UTC' AS completed_at,
(s.shipped_at_local AT TIME ZONE 'Europe/Dublin')
- (o.completed_at AT TIME ZONE 'UTC') AS time_to_dispatch,
((o.completed_at AT TIME ZONE 'UTC') AT TIME ZONE 'Europe/Dublin')::time
< time '14:00' AS before_cut_off
FROM stg_3pl_shipments s
JOIN spree_orders o ON o.number = s.order_number;
One caveat no SQL can solve: on the night winter time starts and the clocks go back an hour, one hour of Irish local time happens twice. A local time stamp in that hour, with no zone, could be either. Ask the 3PL to send UTC or an offset, and until then flag rows in that hour rather than guess.
In BigQuery, TIMESTAMP is an absolute moment and DATETIME is a wall clock value without a zone19. DATE(ts, 'Europe/Dublin') and TIMESTAMP_TRUNC(ts, MONTH, 'Europe/Dublin') take the zone as an argument2021. To compare GA4 with the shop by day, either use event_date and check the property's time zone setting, or convert event_timestamp yourself. Do not mix the two.
BETWEEN with time stamps: the missing Cyber Monday
BETWEEN a AND b includes both ends4. For whole numbers that is grand. For time stamps it is a trap twice over, which is why the PostgreSQL wiki says not to use BETWEEN, especially with time stamps7.
Example: November without its last day
-- PostgreSQL: wrong
SELECT COUNT(*), SUM(total)
FROM spree_orders
WHERE completed_at BETWEEN '2026-11-01' AND '2026-11-30';
The text '2026-11-30' becomes midnight at the start of 30 November. Every order after 00:00:00 on that day is excluded. In 2026, 30 November is Cyber Monday. Shannonside took 141 orders worth €11,844 that day, so the query reports 1,839 orders and €154,476 instead of 1,980 and €166,320. Move the upper bound to '2026-12-01' and you include orders at exactly midnight on 1 December, which then appear in December as well. The second error is smaller, but it double counts across months.
The fix is the half open interval, which includes the start and excludes the end:
-- PostgreSQL: right, every moment of November exactly once
WHERE completed_at >= '2026-11-01' AND completed_at < '2026-12-01'
Consecutive half open months tile time with no gaps and no overlaps. Combine it with the time zone conversion above when the boundaries are local midnights.
DISTINCT as a smell: hiding the duplicates you created
When a query returns duplicates, adding DISTINCT is tempting. It makes the symptom go away, and with it the evidence. Duplicates in a result almost always mean a join at the wrong grain. DISTINCT does not fix that. It hides it, and costs a sort or hash over the whole result.
The worst form is SUM(DISTINCT ...). It adds up the different values, so two genuinely different orders with the same total collapse into one.
Example: SUM(DISTINCT) on the three test orders
Back to R100 (€84), R101 (€98) and R102 (€84). After the fanned join, someone notices the inflated sum and writes SUM(DISTINCT o.total):
-- PostgreSQL: wrong in a new way
SELECT SUM(DISTINCT o.total)
FROM spree_orders o
JOIN spree_line_items li ON li.order_id = o.id
JOIN spree_payments p ON p.order_id = o.id;
It returns €182, which is €84 + €98. R100 and R102 both total €84, so one of them vanished. In a shop with an average order value of €84, thousands of orders share a total, and the error is large. The fix is the one from the fan out section: get the grain right first. Use DISTINCT only when "the set of different values" is really the question, such as "which countries did the shop ship to?".
Window functions done right
A window function calculates across a set of related rows, its window, and keeps every row. The OVER clause defines the window: PARTITION BY splits rows into groups, ORDER BY sorts them inside each group22. Three uses come up every week in data engineering, and each has a trap.
Deduplication with ROW_NUMBER
The 3PL resends a shipment row every time its status changes, so the same shipment_ref appears in several daily files. Callum wants the latest status per shipment. ROW_NUMBER() numbers the rows in each partition 1, 2, 3, and he keeps row 1.
Two traps. First, ties: if two rows share the same file_date, which one is "first" is arbitrary and may change between runs. Always add a tie breaker that is unique, such as the load time and the file line number. Second, NULLs: PostgreSQL sorts NULL as larger than any value, so ORDER BY file_date DESC puts NULLs first23. BigQuery does the opposite: NULLS LAST is its default for descending order24. The same deduplication query keeps different rows on the two engines.
Example: the corrupt row that won
Shipment S1 has three rows: "dispatched" from the file of 2 November, "delivered" from 4 November, and a row with status "corrupt" and no file date, from a file that failed to parse.
-- PostgreSQL: wrong, the NULL date sorts first in DESC order
SELECT *
FROM (
SELECT s.*,
ROW_NUMBER() OVER (PARTITION BY shipment_ref ORDER BY file_date DESC) AS rn
FROM raw_3pl_shipments s
) x
WHERE rn = 1;
Result: S1, status "corrupt". The fix states the NULL handling and adds a tie breaker:
-- PostgreSQL: right, and deterministic
SELECT *
FROM (
SELECT s.*,
ROW_NUMBER() OVER (
PARTITION BY shipment_ref
ORDER BY file_date DESC NULLS LAST, loaded_at DESC, file_line DESC
) AS rn
FROM raw_3pl_shipments s
) x
WHERE rn = 1;
Result: S1, status "delivered". PostgreSQL also offers DISTINCT ON (shipment_ref) with the same ORDER BY, which keeps the first row of each group, and its documentation warns that the first row is unpredictable unless ORDER BY decides it25. In BigQuery, the QUALIFY clause filters on a window function directly24, so the same deduplication reads like this:
-- BigQuery
SELECT *
FROM shannonside_raw.threepl_shipments
QUALIFY ROW_NUMBER() OVER (
PARTITION BY shipment_ref
ORDER BY file_date DESC NULLS LAST, loaded_at DESC, file_line DESC
) = 1;
The 3PL's resent rows are also why the cleaning chapters keep raw files untouched and deduplicate in a later layer.
Running totals and the default frame
For each row, a window function with ORDER BY works on a frame: by default, every row from the start of the partition up to the current row, plus any following rows that are equal to it in the ORDER BY22. Rows that tie are called peers, and they all get the same running total. That is rarely what anyone means.
Example: two rows on 2 November
A daily table has two rows for 2 November, €5,600 from the shop and €350 from a marketplace:
-- PostgreSQL
SELECT d, revenue,
SUM(revenue) OVER (ORDER BY d) AS default_frame,
SUM(revenue) OVER (ORDER BY d, source
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rows_frame
FROM daily_revenue;
| d | revenue | default_frame | rows_frame |
|---|---|---|---|
2026-11-01 | 4,780 | 4,780 | 4,780 |
2026-11-02 | 350 | 10,730 | 5,130 |
2026-11-02 | 5,600 | 10,730 | 10,730 |
2026-11-03 | 6,070 | 16,800 | 16,800 |
With the default frame, both 2 November rows show €10,730, so the first of the two rows already includes the other one. ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, with a unique sort order, gives a true row by row running total. The same default frame makes last_value() return the current row instead of the last one, which PostgreSQL's documentation calls likely to give unhelpful results26. Better still for a daily running total: aggregate to one row per day first, then run the window.
LAG for gaps
LAG(x) returns the value of x from the previous row in the window. It is the natural tool for "time since the last one".
Example: repeat purchase gaps and a missing file
A customer ordered on 3 February, 21 April and 30 November 2026:
-- PostgreSQL
SELECT user_id,
completed_at::date AS order_date,
completed_at::date
- LAG(completed_at::date) OVER (PARTITION BY user_id ORDER BY completed_at, id)
AS days_since_previous
FROM spree_orders
WHERE user_id = 5120 AND completed_at IS NOT NULL;
| order_date | days_since_previous |
|---|---|
2026-02-03 | NULL |
2026-04-21 | 77 |
2026-11-30 | 223 |
The first order has no previous one, so its gap is NULL, and it should stay NULL rather than become zero: an average gap that counted it as zero would fall. (Strictly, the date cast here should use Irish time, as in the time zone section.)
The same tool finds holes in a feed. Callum lists the dates of the 3PL files that arrived and computes the gap to the previous one. Any gap above one day means a missing file: on 18 November the gap is 2, because the file for Tuesday 17 November never came. For a full list of missing days, an anti join against generate_series('2026-11-01'::date, '2026-11-30', interval '1 day') is even clearer.
CTEs: write the query as a list of steps
A long query with nested subqueries is hard to read and harder to check. A CTE gives each step a name, and the query reads from top to bottom like a recipe. dbt's style guide recommends "import" CTEs at the top, one per source table, selecting only the columns needed, followed by the logical steps and a final select27.
The fixed fan out query earlier is already in this shape. In a dbt model it looks like this:
-- dbt model: models/marts/fct_orders.sql (PostgreSQL target)
-- grain: one row per completed order
with orders as (
select id as order_id, number as order_number, total, completed_at
from {{ ref('stg_spree_orders') }}
where completed_at is not null
),
line_items as (
select order_id, quantity, price
from {{ ref('stg_spree_line_items') }}
),
payments as (
select order_id, amount
from {{ ref('stg_spree_payments') }}
where state = 'completed'
),
line_totals as (
select order_id,
count(*) as line_count,
sum(quantity * price) as item_revenue
from line_items
group by order_id
),
paid as (
select order_id, sum(amount) as amount_paid
from payments
group by order_id
),
final as (
select o.order_id,
o.order_number,
o.completed_at,
o.total,
coalesce(lt.line_count, 0) as line_count,
coalesce(lt.item_revenue, 0) as item_revenue,
coalesce(p.amount_paid, 0) as amount_paid
from orders o
left join line_totals lt on lt.order_id = o.order_id
left join paid p on p.order_id = o.order_id
)
select * from final
Every CTE states its grain by its GROUP BY, and you can select from any step on its own to check it. A note on speed: since version 12, PostgreSQL folds a CTE that is referenced once into the main query, and computes it separately when referenced more than once, with MATERIALIZED and NOT MATERIALIZED to override that choice28. Readable CTEs no longer cost you a slow plan by default.
Testing a query against known totals
Every trap in this chapter produces a number that is wrong by a measurable amount. So measure it. Before a query feeds a report, it has to agree with a total you already trust. I work test first in software (if the idea is new, test driven development explained shows how), and queries deserve the same: decide the expected number, then write the query, then prove they match.
Useful control totals for a shop:
| Control | Compared with | Catches |
|---|---|---|
| Row count at the output grain | COUNT(DISTINCT order_id) | Fan out, wrong GROUP BY |
| Sum of revenue in the result | Sum of spree_orders.total for the same period | Fan out, lost rows, BETWEEN errors |
| Rows in versus rows out of each join | Count before and after | Inner joins on NULL keys, WHERE on outer joins |
| Card and wallet payments | Stripe and PayPal settlement files | Failed payments counted, refunds missed |
| Monthly totals in local time | The finance team's month end figures | Time zone and boundary errors |
How far apart the shop, GA4 and the payment providers may legitimately be, and why, is covered in when analytics, ads and orders disagree.
Example: three dbt tests that pin fct_orders
dbt runs two kinds of tests. Data tests are queries that return failing rows: zero rows means pass29. Unit tests, available since dbt 1.8, feed a model small invented inputs and compare its output with the expected rows30.
The grain test, as generic data tests in the model's YAML (dbt still accepts the older tests: key as an alias of data_tests:29):
# models/marts/fct_orders.yml
models:
- name: fct_orders
columns:
- name: order_id
data_tests:
- unique
- not_null
The control total, as a singular data test that returns a row only if the model and the source disagree:
-- tests/assert_fct_orders_revenue_matches_source.sql
with model as (
select coalesce(sum(total), 0) as revenue, count(*) as orders
from {{ ref('fct_orders') }}
),
source as (
select coalesce(sum(total), 0) as revenue, count(*) as orders
from {{ ref('stg_spree_orders') }}
where completed_at is not null
)
select model.revenue, source.revenue, model.orders, source.orders
from model cross join source
where model.revenue <> source.revenue
or model.orders <> source.orders
And the fan out guard, as a unit test that uses the three orders from the start of this chapter. If anyone ever joins payments before aggregating, R101 doubles and the test fails before the change reaches production:
# models/marts/fct_orders.yml (continued)
unit_tests:
- name: fct_orders_does_not_fan_out
model: fct_orders
given:
- input: ref('stg_spree_orders')
rows:
- {id: 1, number: R100, total: 84.00, completed_at: "2026-11-03 10:15:00"}
- {id: 2, number: R101, total: 98.00, completed_at: "2026-11-03 11:40:00"}
- {id: 3, number: R102, total: 84.00, completed_at: "2026-11-03 19:05:00"}
- input: ref('stg_spree_line_items')
rows:
- {order_id: 1, quantity: 1, price: 35.00}
- {order_id: 1, quantity: 1, price: 49.00}
- {order_id: 2, quantity: 1, price: 24.00}
- {order_id: 2, quantity: 2, price: 18.00}
- {order_id: 2, quantity: 1, price: 38.00}
- {order_id: 3, quantity: 1, price: 84.00}
- input: ref('stg_spree_payments')
rows:
- {order_id: 1, amount: 84.00, state: completed}
- {order_id: 2, amount: 98.00, state: failed}
- {order_id: 2, amount: 98.00, state: completed}
- {order_id: 3, amount: 84.00, state: completed}
expect:
rows:
- {order_id: 1, line_count: 2, item_revenue: 84.00, amount_paid: 84.00}
- {order_id: 2, line_count: 3, item_revenue: 98.00, amount_paid: 98.00}
- {order_id: 3, line_count: 1, item_revenue: 84.00, amount_paid: 84.00}
The expect block lists only the columns it checks, which dbt allows. Testing pipelines as a whole, with data contracts and test gates, has its own chapter later in this series.
Debugging a total that looks wrong
When a number looks off, the worst move is to change the query until the number looks right. That is how DISTINCT and fudge factors get in. A fixed order of checks finds the cause instead:
The definitions step deserves a word. "Revenue" can mean the order total including VAT and shipping, item revenue only, net of VAT, net of refunds, or only orders still in the Solidus state "complete". That last one is a quiet trap of its own: Solidus moves an order from complete to returned or awaiting return when items come back, and to canceled when it is cancelled31. A query filtered on state = 'complete' shows last month's revenue falling every time a return is processed. Decide whether you want orders as placed or orders as they stand today, and write it down. The eCommerce metrics glossary and the purchase event done right define the revenue variants.
Example: Callum debugs the €467,660
Niamh's dashboard shows €467,660 for November. Callum follows the chart. Expected: €166,320 from spree_orders. Row count at the output grain: the query returns 4,260 rows for 1,980 orders, so step c is a "no". He counts after each join: 1,980 rows from orders, 4,260 after joining line items. The join to line items is the fan out. He rewrites it with the line totals CTE, the revenue drops to €166,320, and he adds the singular test above so it can never quietly drift again. Fifteen minutes, one test, and the number is pinned.
A checklist of silent errors
| Trap | Symptom | Fix |
|---|---|---|
| Join fan out | Totals too high, rows per order above 1 | Aggregate children to the parent's grain, then join |
| Many to many | Category totals exceed the shop total | Primary category, allocation, or report overlaps separately |
| NULL join keys | Fewer rows than expected | LEFT JOIN, count unmatched, test keys for NULL |
| NOT IN with NULL | Zero rows | NOT EXISTS |
| Wrong COUNT | Customers equal accounts or emails | Name what you count, resolve people properly |
| Aggregates and NULL | Averages too kind, blank days | Report the NULL count, COALESCE where zero is true |
| Integer division | Rates of 0, or truncated | Numeric arithmetic, NULLIF for zero |
| Floats for money | Sums off by pennies | Cast to numeric in staging |
| Average of averages | Rates too high or too low | Sum numerators and denominators, then divide |
| GROUP BY at the wrong grain | One customer in several rows | Group by the key, add attributes from a dimension |
| WHERE on a LEFT JOIN | Missing zero rows | Aggregate first, or filter in ON |
| Time zones | Days and months shifted by an hour | Store absolute moments, convert with named zones |
| BETWEEN with time stamps | Last day missing, or midnight doubled | Half open intervals |
| DISTINCT as a fix | Plausible but wrong totals | Find the join at the wrong grain |
| ROW_NUMBER without tie breaker | Results change between runs | Unique ORDER BY, explicit NULLS LAST |
| Default window frame | Peers share a running total | ROWS frame, unique order |
Conclusion
SQL rarely lies on purpose. It answers exactly the question you typed, which is often not the question you meant. Nearly every silent error in this chapter is a mismatch of grain: a join that multiplies rows, a GROUP BY that splits them, an average that weighs them wrongly, a filter that drops them. The rest are mismatches of type and time: integers that truncate, floats that drift, UTC that looks like local time, a BETWEEN that stops at midnight.
The defence is not cleverness. It is habit. State the grain of every query, count rows after every join, use NOT EXISTS and half open intervals by reflex, keep numerators and denominators, convert time with named zones, and pin every important number to a total you already trust with a test that runs before every release. Do that, and when a number is wrong you find out in your test run, not in Niamh's board meeting. The next chapter takes the same idea from single queries to whole tables: how to measure whether your data can be trusted at all.
