Reconcile SQL results at the right grain
Control join multiplicity, aggregation, ordering, table creation and historical reproducibility.
Reconcile SQL results at the right grain
Work through the decision
A daily dashboard subtracts refunds from sales. Yesterday one sale received two partial refunds. The joined result now reports more gross revenue even though no sales were added. How should the query be repaired?
Check your reasoning
Write down one row per sale as the required grain. Aggregate refunds by sale ID first, then left join that summary to sales. Replace a missing refund total with zero only because the business definition treats absence of refunds that way. Check both row count and monetary totals, including a sale with no refunds.
Compare the choices
- Preaggregate and left join
- Reduce many-side transactions to one row per business key and retain unmatched facts. Verify counts and sums at the declared grain.
- UNION ALL
- Append compatible result sets while preserving duplicate rows. Use deduplication only under an explicit business rule.
- Deterministic top-N ordering
- Sort by the business metric and a stable tie breaker before applying LIMIT. Use a defined period and grouping grain.
- Delta time travel
- Query a specified retained historical version or timestamp. Ensure required data and transaction history remain available for the relevant inputs.
- Managed CTAS
- Use CREATE TABLE AS SELECT with a suitable managed destination to persist a governed result from compatible sources. Consider independent lifecycle when choosing external storage.
Test the decision
Filter input dates with an explicit boundary and use a stable tie breaker for top-N results. Use the right table type for output ownership and storage lifecycle. To reproduce an older report, record versions for every relevant input and verify the underlying Delta data files remain available.
Practice the guide skills
- Reconcile ticket and known-fare counts. Watch 50:32 · Continue at 52:24
Check your answer
COUNT(*) includes all rows, COUNT(fare) skips nulls, AVG ignores nulls and approximate distinct counts trade exactness for efficiency. Compare aggregates at the same grain.
- Combine ticket sales and refunds without losing unrefunded sales. Watch 55:48 · Continue at 56:58 · Continue at 58:45
Check your answer
Aggregate the many-side to the sale key, then LEFT JOIN. Validate composite keys where necessary. UNION ALL preserves repeated rows, whereas UNION removes duplicate result rows.
- Select the top three stations for a given service day. Watch 53:37 · Continue at 53:56
Check your answer
Filter the day before grouping, order by revenue descending and add a stable station tie breaker before LIMIT. Use HAVING for conditions on computed groups.
- Unify CSV references and Parquet or Delta sales under Unity Catalog. Watch 11:12 · Continue at 11:39 · Continue at 1:01:07 · Continue at 1:01:36
Check your answer
Read each source with a suitable schema and type alignment, then use a managed CTAS when the catalog should control storage. Use a registered external location for an external table and agree on its independent file lifecycle.
- Reproduce a prior Delta report. Watch 1:09:01 · Continue at 1:09:49
Check your answer
Identify the committed version through table history and use VERSION AS OF or TIMESTAMP AS OF with a retained snapshot. Required data files must still exist.
Official objectives for this lesson
Lab · Reconcile sales and partial refunds in SQL
Run this Python 3 script with its built-in SQLite engine. The SQL uses joins and aggregates shared with Databricks SQL. The fixture has three sales, two partial refunds for one sale and an unrefunded sale with the same price as another. Predict the gross and net totals before running python lab.py.
import sqlite3
with sqlite3.connect(":memory:") as db:
db.executescript("""
CREATE TABLE sales(id INTEGER PRIMARY KEY, cents INTEGER NOT NULL);
CREATE TABLE refunds(id INTEGER PRIMARY KEY, sale_id INTEGER, cents INTEGER);
INSERT INTO sales VALUES (1, 1200), (2, 800), (3, 1200);
INSERT INTO refunds VALUES (11, 1, 200), (12, 1, 100), (13, 2, 50);
""")
direct = """
SELECT COUNT(*), SUM(s.cents), SUM(s.cents - COALESCE(r.cents, 0))
FROM sales AS s LEFT JOIN refunds AS r ON s.id = r.sale_id
"""
repaired = """
WITH by_sale AS (
SELECT sale_id, SUM(cents) AS refund_cents
FROM refunds GROUP BY sale_id
)
SELECT COUNT(*), SUM(s.cents),
SUM(s.cents - COALESCE(r.refund_cents, 0))
FROM sales AS s LEFT JOIN by_sale AS r ON s.id = r.sale_id
"""
for label, query in [("direct", direct), ("reconciled", repaired)]:
print(label, *db.execute(query).fetchone())
Check the result
direct 4 4400 4050 reconciled 3 3200 2850
Gross receipts are 1,200 + 800 + 1,200 = 3,200 cents. Refunds total 350, giving net revenue of 2,850. The direct join repeats sale 1. SUM(DISTINCT amount) would also be wrong because two legitimate sales have the same price. Add a 25-cent refund to sale 3. The corrected row count and gross should hold steady while net falls by 25.
Related lesson · SQL commands and logic
Reconcile SQL results at the right grain quiz
Answer 3 questions. Check each answer for an explanation.