01 / 21
=

Reconciling
Aggregates in SQL

Learn how to verify and match aggregate results across different query approaches, ensuring your totals, counts, and averages tell a consistent story.

SQL

What Are Aggregates?

Aggregate functions collapse many rows into a single summary value. They answer "big picture" questions about your data: how much, how many, or what's the average.

COUNT
Number of rows (or non-null values) in a set
SUM
Total of a numeric column across all matching rows
AVG
Arithmetic mean: \( \frac{\text{SUM}(x)}{\text{COUNT}(x)} \)

What Does Reconciling Mean?

Reconciling means comparing aggregate results from two or more queries that should represent the same underlying fact, and verifying they agree. If they don't, you have a data bug.

Query A SUM = 5,000 Query B SUM = 5,000 = ✓ Reconciled Query C SUM = 5,000 Query D SUM = 6,200 ✕ ✕ Mismatch

Why Reconciling Matters

In real applications, the same fact can be queried many ways. If a dashboard total disagrees with a detail report, stakeholders lose trust. Reconciliation catches bugs before they become business problems.

1
Data integrity: Confirms that joins, filters, and groupings haven't silently duplicated or dropped rows.
2
Refactoring safety: When you rewrite a query for performance, reconciliation proves the new version is equivalent.
3
Migration validation: After moving data between systems, aggregate checks are the fastest sanity test.

The Golden Rule of Aggregates

Formally, if Query A and Query B both aim to compute the total revenue for January:

The key insight: aggregate functions are deterministic over a fixed set of rows. If the row sets differ, the aggregates will differ.

Same Rows, Same Result

orders table id amount 1 100 2 200 3 150 4 50 Query A 4 rows Query B 4 rows SUM = 500 ✓ Match But if Query B uses a JOIN that duplicates row 2... Query B' 5 rows (dup!) SUM = 700 ✕ Mismatch

GROUP BY vs. Total Aggregate

A crucial reconciliation check: the sum of grouped subtotals must equal the ungrouped total.

Ungrouped
SELECT SUM(amount) FROM orders
Returns one row: the grand total
Grouped
SELECT region, SUM(amount) FROM orders GROUP BY region
Returns one row per region

COUNT(*) vs. COUNT(column)

COUNT(*) COUNT(column)
Counts what? Every row, regardless of NULLs Only rows where column is NOT NULL
NULL row present? Included Excluded
Can they differ? Yes, when NULLs exist: COUNT(*) > COUNT(col)
Reconciliation risk Overcounting if expected non-null Undercounting if NULLs unexpected

JOINs and Duplicate Rows

When you JOIN two tables, a one-to-many relationship multiplies rows. If you aggregate on the "one" side after joining, you'll count values multiple times.

-- Dangerous: SUM inflated by duplicates SELECT SUM(o.amount) FROM orders o JOIN order_items oi ON o.id = oi.order_id; -- Safe: aggregate before or after correctly SELECT SUM(amount) FROM orders;

How to Reconcile Step by Step

1
Write the "source of truth" query: A simple, direct aggregate with no joins or subqueries.
2
Write the query under test: The more complex version (with JOINs, CTEs, subqueries, etc.).
3
Compare row counts: Check COUNT(*) from both. If they differ, investigate duplicate or missing rows.
4
Compare key aggregates: Check SUM, AVG, MIN, MAX. All should match.
5
Drill into differences: Use EXCEPT or anti-joins to find the exact rows causing the mismatch.

Example 1: Basic Reconciliation

Two analysts compute total sales for Q1. Do their queries agree?

-- Analyst A: direct sum SELECT SUM(amount) AS total FROM sales WHERE quarter = 'Q1'; -- Result: 42,000 -- Analyst B: sum of regional subtotals SELECT SUM(regional_total) FROM ( SELECT region, SUM(amount) AS regional_total FROM sales WHERE quarter = 'Q1' GROUP BY region ) sub; -- Result: 42,000

Example 2: JOIN Inflation

An analyst joins orders to order_items and computes total order amounts. Something looks off.

-- Source of truth SELECT SUM(amount) FROM orders; -- Result: 10,000 -- Query under test (with JOIN) SELECT SUM(o.amount) FROM orders o JOIN order_items oi ON o.id = oi.order_id; -- Result: 28,500 ← inflated!

Example 3: NULL Mismatch

Two queries count students. One uses COUNT(*), the other uses COUNT(email).

SELECT COUNT(*) FROM students; -- Result: 150 SELECT COUNT(email) FROM students; -- Result: 142

Drilling Down with EXCEPT

When aggregates don't match, use EXCEPT to find the exact rows that differ between two result sets.

-- Rows in Query A but NOT in Query B SELECT id, amount FROM query_a_results EXCEPT SELECT id, amount FROM query_b_results; -- Rows in Query B but NOT in Query A SELECT id, amount FROM query_b_results EXCEPT SELECT id, amount FROM query_a_results;

Common Mistakes

✕ Aggregating after a 1:N JOIN
Joining before aggregating inflates SUM and COUNT. Always aggregate first or use DISTINCT.
✕ Ignoring NULLs
COUNT(column) skips NULLs silently. Use COUNT(*) when you need all rows, or explicitly handle NULLs.
✕ Mismatched WHERE filters
Different date ranges, status filters, or implicit filters from INNER JOINs change the row set and break reconciliation.

Summary: Reconciliation Checklist

Check What to Compare Common Cause of Mismatch
Row count COUNT(*) from both queries Duplicate rows from JOINs
Total sum SUM(col) from both queries 1:N JOIN inflation
NULL audit COUNT(*) vs. COUNT(col) Unexpected NULL values
Group rollup SUM of grouped SUMs vs. total SUM Missing group or filter mismatch
Exact rows EXCEPT in both directions Filter or JOIN logic errors

Question 1 of 5

Query A returns SUM(amount) = 12,000 from the orders table. Query B joins orders to line_items (a 1:N relationship) and returns SUM(orders.amount) = 36,000. What is the most likely cause?

Question 2 of 5

COUNT(*) returns 500 and COUNT(phone) returns 480 on the same table. What can you conclude?

Question 3 of 5

You GROUP BY region and compute SUM(revenue) for each region. The sum of those subtotals is 95,000, but a direct SUM(revenue) without GROUP BY returns 100,000. What is the most likely cause?

Question 4 of 5

Which SQL technique is best for identifying the specific rows that cause a mismatch between two query results?

Question 5 of 5

An analyst joins customers to orders and computes COUNT(*). The result is higher than COUNT(*) from the customers table alone. Which of the following is NOT a possible explanation?