Domdhi logoDOMDHI.OS
BACK_TO_COURSE

What You Need to Know to Judge SQL

Joins: Where Wrong Numbers Come From

The Join That Doubles Your Money

One order. Two lines, $40 and $60, so the order is worth $100. Two payments of $50, so it's paid in full. Ask for both totals in one query:

-- WRONG
SELECT o.OrderId,
       SUM(l.Quantity * l.UnitPrice) AS OrderTotal,
       SUM(p.Amount)                 AS Paid
FROM dbo.Orders AS o
JOIN dbo.OrderLines AS l ON l.OrderId = o.OrderId
JOIN dbo.Payments   AS p ON p.OrderId = o.OrderId
GROUP BY o.OrderId;
OrderId OrderTotal Paid
1 200.00 200.00

Both numbers doubled. Every line paired up with every payment: 2 × 2 = 4 rows, and the sums added all four. It's called fan-out, and it's dangerous because the result looks right. The totals even match each other.

The fix: shrink each side to one row per order before joining.

-- RIGHT
WITH LineTotals AS (
    SELECT OrderId, SUM(Quantity * UnitPrice) AS OrderTotal
    FROM dbo.OrderLines
    GROUP BY OrderId
),
PaymentTotals AS (
    SELECT OrderId, SUM(Amount) AS Paid
    FROM dbo.Payments
    GROUP BY OrderId
)
SELECT o.OrderId, lt.OrderTotal, pt.Paid
FROM dbo.Orders AS o
LEFT JOIN LineTotals    AS lt ON lt.OrderId = o.OrderId
LEFT JOIN PaymentTotals AS pt ON pt.OrderId = o.OrderId;

Now it says 100.00 and 100.00.

Two More That Run Clean and Lie

1. The LEFT JOIN that isn't. LEFT JOIN keeps every customer, including the ones with no orders. Then one line in the WHERE throws them back out:

-- WRONG: drops customers with no shipped orders
SELECT c.CustomerId, o.OrderId
FROM dbo.Customers AS c
LEFT JOIN dbo.Orders AS o ON o.CustomerId = c.CustomerId
WHERE o.Status = 'Shipped';

-- RIGHT: the condition goes in the join
SELECT c.CustomerId, o.OrderId
FROM dbo.Customers AS c
LEFT JOIN dbo.Orders AS o ON o.CustomerId = c.CustomerId
                         AND o.Status = 'Shipped';

In a test database of 10,000 customers, the wrong one returned rows for only 8,550 different customers. The right one covers all 10,000. 1,450 customers gone, no error.

2. NOT IN with a NULL. If the list inside NOT IN (...) contains a single NULL, you get zero rows back. Use NOT EXISTS, which doesn't have the problem:

-- Customers who never ordered
SELECT c.CustomerId, c.Name
FROM dbo.Customers AS c
WHERE NOT EXISTS (
    SELECT 1 FROM dbo.Orders AS o
    WHERE o.CustomerId = c.CustomerId
);
WARNING

When you see DISTINCT in AI-written SQL, ask why it's there. Sometimes it's right. Often it's hiding a fan-out. In the order above, SUM(DISTINCT p.Amount) gives $50, because two real $50 payments look like one duplicate. Wrong in the other direction.

QUIZ

An order has 3 lines and 2 payments. You join all three tables and SUM the payments. How far off is the total?

Sign in to track lesson progress and earn a certificate.SIGN IN TO SAVE PROGRESS