Aggregate order items and payments before joining in SQLite
Two one-to-many joins can multiply amounts. A tested SQLite example groups items and settled payments by order before combining the totals.
In this article
Define what a report row represents
Suppose an accounting screen displays the invoiced amount and settled receipts for each order. An order may have two item lines and three payment records. Joining both detail tables to the order and aggregating at the end looks like a reasonable first pass. The intermediate rows do not pair an item with the payment that funded it. Each item on that order joins to every eligible payment on the same order, repeating monetary amounts according to the number of matches on the other side. SQLite can execute that query successfully, and there may be no exception or warning for a dashboard to show. Begin by writing down the intended result grain. The identifier is the order number, and both amounts describe that one order. Orders form the starting set for the report. Keep examples with several detail rows in the test data so the join pattern can actually surface.
Inspect the six joined rows
Order 101 has two item lines worth 2,500 cents each. It has three settled payments of 2,500, 2,000 and 400 cents. A join that combines the raw item and payment rows on order ID produces six rows. The billed amount becomes 15,000 cents because each item is counted three times. The paid amount becomes 9,800 cents because each payment is counted twice. The actual totals are 5,000 and 4,900 cents. During debugging, remove the GROUP BY and display the order, item and payment identifiers together. You can then see that every item identifier repeats against every payment identifier. Changing the aggregate to SUM(DISTINCT line_cents) discards a genuine item in this fixture. Both lines have the same price, so the expression returns 2,500 cents. Equality of amounts says very little about how many invoices, items or payments occurred.
Group each source by order first
The item_totals expression reads only order items and computes a billed amount for each order. The payment_totals expression filters for settled payments first, then computes received cash for each order. Both results contain at most one row for any order ID. The final query begins with orders and attaches both results using separate LEFT JOIN clauses. A common table expression names the business operation, and SQLite remains free to choose how it runs that operation. The technique also applies to separately recorded refunds or shipping credits. Define the amount, status rule, reporting period and grouping key for each source before adding it. If the detail table itself contains duplicates, work out the identity of the transaction there. Grouping by order can prevent multiplication across sources, but it will still include multiple physical rows that represent the same real transaction.
WITH item_totals AS (
SELECT order_id, SUM(line_cents) AS billed_cents
FROM order_items
GROUP BY order_id
), payment_totals AS (
SELECT order_id, SUM(amount_cents) AS paid_cents
FROM payments
WHERE status = 'settled'
GROUP BY order_id
)
SELECT o.id,
COALESCE(i.billed_cents, 0) AS billed_cents,
COALESCE(p.paid_cents, 0) AS paid_cents
FROM orders AS o
LEFT JOIN item_totals AS i ON i.order_id = o.id
LEFT JOIN payment_totals AS p ON p.order_id = o.id
ORDER BY o.id;
Decide how to represent absent payments
Order 102 has no item rows and only a pending payment. The sample returns zero cents for both fields. Order 103 has an item worth 3,000 cents and a pending payment. Its billed amount is 3,000 and its settled amount is zero. These rows test the placement of the status predicate. Putting a payment-only condition in the final WHERE clause can filter away orders that have no matching payment record. Filtering the payment expression before grouping leaves the order on the left side of the join. COALESCE makes the report show zero when a subtotal row is absent. Retain NULL or add a data status field when the business treats an unknown amount differently from zero. The sample stores amounts as non-null integer cents. For reports with multiple currencies, group amounts by currency or convert them using a documented exchange rate and rounding rule.
Keep an independent reconciliation
The fixture asserts the three expected rows: order 101 has 5,000 billed and 4,900 paid, 102 has zero and zero, and 103 has 3,000 and zero. A separate assertion records the two inflated values from the faulty query. That is useful evidence that the sample actually reproduces the defect. For a production report, compare the number of selected orders with the number of distinct order IDs in the result. Then reconcile the sum of report payments against a separate aggregate over settled payments for the same order population. An equality test on one grand total can miss errors that cancel out, so retain a few order-level examples with known results. Include repeated prices, orders with pending payments, and orders without any payments. Fixtures can be rebuilt after a schema or database upgrade so the test stays independent of changing production records.
Measure the plan with representative data
Once the totals reconcile, inspect EXPLAIN QUERY PLAN on a dataset representative of the workload. An index beginning with order_id may help for a restricted list of orders. For the settled payment query, measure candidates involving status and order_id against the real distribution of states. A screen showing a few order IDs has different costs from a full-period report. Push the selected orders into both aggregate inputs when measurement shows that a narrow query is still grouping a large history. Compare elapsed times and the volume of input rows alongside the write costs of another index. If a materialized balance is eventually needed, define how to handle status changes, refunds, multiple currencies and rebuilds before persisting it. Run the exact-result assertions after every performance change. The three expected order rows should survive a change in the planner or in the shape of an index.
Reader discussion
Which alternative architecture would you try for the same problem?
No comments yet. Be the first to contribute.
Write a comment