Practical SQL
SQL joins for data engineering: avoid duplicate revenue
A successful SQL query can still report incorrect revenue. Learn to identify one-to-many joins and aggregate payments at order level before joining.
Updated November 2026
Book free 15-min career guidanceBy Ankit Kothari · Published 1 December 2026
Build the sample tables
Use SQLite and synthetic orders. Amounts are integer rupees for this exercise.
CREATE TABLE orders (id INTEGER PRIMARY KEY, amount INTEGER);
CREATE TABLE payments (id INTEGER PRIMARY KEY, order_id INTEGER, amount INTEGER);
INSERT INTO orders VALUES (101,500),(102,750),(103,250);
INSERT INTO payments VALUES (1,101,300),(2,101,200),(3,102,750),(4,103,250);Find the incorrect total
SELECT SUM(o.amount)
FROM orders o JOIN payments p ON o.id=p.order_id;Expected: 2000 instead of 1500. Order 101 matches two payment rows, so its amount is counted twice.
Aggregate before joining
WITH p AS (
SELECT order_id, SUM(amount) AS paid
FROM payments GROUP BY order_id
)
SELECT SUM(o.amount) AS order_total,
SUM(COALESCE(p.paid,0)) AS paid_total
FROM orders o LEFT JOIN p ON o.id=p.order_id;Expected: 1500 and 1500. The payment summary has one row per order. A left join preserves unpaid orders.
Test the edge cases
Add order 104 worth 500 with no payment. The corrected totals should become 2000 and 1500. This also demonstrates why SUM(DISTINCT amount) is wrong. In production, separately check orphan payments, refunds, currency, payment status and the definition of recognized revenue. Order totals are not necessarily accounting revenue.
Apply your testing experience
Manual testers and support professionals can practise checking business keys, row counts and totals before and after joins. Explore the interview guide, manual testing career roadmap and Gaur City data engineering course.
Frequently asked questions
Why not use SUM(DISTINCT amount)?
Different orders can have equal amounts. Deduplicate by business key, not by monetary value.
Want a guided version of this?
Step2Success runs a 90-day Python and data engineering program for working professionals, with classroom learning in Gaur City 2, Noida Extension and online sessions. Plans start at ₹9,999. See the career switch roadmap or the Gaur City course page.
Talk before you join
Tell us your current role, your experience and your goal. We will suggest the right plan and share the latest syllabus and batch timings. Classes run at Mahagun Mywoods, Gaur City 2, Noida Extension and live online. Rated 4.9 on Google (93 reviews): read the reviews.
Book free 15-min career guidance