r/SQL • • 29d ago

Discussion This query runs fine and the total is wrong. Where?

SELECT c.region, SUM(o.amount) AS revenue
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
LEFT JOIN refunds r ON r.order_id = o.order_id
WHERE r.status <> 'approved'
GROUP BY c.region;

The goal: revenue per region, minus orders with an approved refund. No errors, the numbers look plausible.

There are two bugs, and they push the total in opposite directions.

1 Upvotes

27 comments sorted by

29

u/fauxmosexual NOLOCK is the secret magic go-faster command 29d ago

WHERE ( r.status <> 'approved' or r.status is null)

Is what you need if you want to include orders that have no entry in the refunds table.

5

u/Awkward-Meeting790 29d ago

close but that still double counts. the join fans out, so an order with 2 non approved refunds shows up twice, and an order with one approved + one rejected refund still gets in through the rejected row. the not exists version further down handles both

4

u/Zestyclose-Turn-3576 28d ago

yes, left joins are IMHO a very bad way of testing for non-existence, for exactly this reason

23

u/Zestyclose-Turn-3576 29d ago

Perhaps this is more semantically clear, if you want there not to be an approved refund on the order.

SELECT
  c.region,
  SUM(o.amount) AS revenue
FROM
  customers c
  LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE
  not exists (
    select null
    from   refunds r
    where  r.order_id = o.order_id and
           r.status   = 'approved'
  )
GROUP BY
  c.region;

9

u/lolcrunchy 29d ago
  1. The query doesn't subtract the refunded amount, it just pulls in approved refunds
  2. An order could have four item, two of which were refunded separately. That would duplicate the order and incorrectly double the revenue for that order.

3

u/MrRoy_SQL 28d ago

bug 1 (total too low): WHERE r.status <> 'approved' throws away every order with no refund at all, because r.status is NULL there and NULL <> 'approved' isn't true. so your normal orders vanish, and regions with no orders disappear too. the left join is basically an inner join now.

bug 2 (total too high): an order with 2 refund rows (say rejected + pending) shows up twice, so its amount gets summed twice. and an order with approved + rejected still sneaks in through the rejected row.

fix is to not join refunds at all, just check for an approved one:

SELECT c.region, COALESCE(SUM(o.amount), 0) AS revenue
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id
AND NOT EXISTS (
SELECT 1 FROM refunds r
WHERE r.order_id = o.order_id
AND r.status = 'approved'
)
GROUP BY c.region;

2

u/reditandfirgetit 28d ago

Use not exists in the where clause if there can be multiple matches in the refunds table

1

u/lord_xl 28d ago

Is there a reason customers and orders is a left join and not inner? All orders have customers, correct?

0

u/Zestyclose-Turn-3576 28d ago

But not all customers have orders, and more importantly there might be a region for which no customers have orders.

1

u/lord_xl 28d ago

The goal: revenue per region, minus orders with an approved refund. No errors, the numbers look plausible.

You're correct. I missed the detail about region only being in the customer table. In the perfect world region would be in the orders table (where the order is shipping) or its own table.

1

u/reditandfirgetit 28d ago

Use not exists in the where clause if there can be multiple matches in the refunds table

1

u/Aggressive_Ad_5454 28d ago

It’s a cardinality thing. If there’s more than one refund for an order, o.amount gets counted multiple times, once for each refund record.

1

u/Lanky_Debate_5267 28d ago edited 28d ago

Two issues: The WHERE clause filters out orders without refunds because NULL <> 'approved' isn't true. Also, multiple refund records can duplicate orders and inflate revenue.
Use NOT EXISTS to fix both:

SELECT c.region, SUM(o.amount) AS revenue
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE NOT EXISTS (
SELECT 1
FROM refunds r
WHERE r.order_id = o.order_id
AND r.status = 'approved'
)
GROUP BY c.region;

This includes orders without refunds, excludes orders with approved refunds, and prevents double-counting.

1

u/baubleglue 27d ago

Replace WHERE with AND

1

u/DiscombobulatedSun54 22d ago

You have made the left join an inner join by not allowing for refund status to be NULL. Very common mistake.

1

u/techforallseasons 29d ago

Other answers are part of the answer, but without knowing the schema - your SUM( ) over a column from a LEFT JOIN'd table could lead to NULL values within the SUM().

That might lead to some regions having a NULL result. a SUM( COALESCE() ) might be useful.

3

u/Wuthering_depths 28d ago

My first thought as well. NULLs can lead to all kinds of problems, so if the outer joined tables are really optional, might need something to make them 0s (if that works with the logic).

4

u/fauxmosexual NOLOCK is the secret magic go-faster command 28d ago edited 28d ago

This isn't correct, nulls don't break a sum in that way. In a sum nulls are just ignored.

2

u/Zestyclose-Turn-3576 28d ago

Indeed! Null is ignored by aggregate functions, except that count of a null doesn't increment the count.

-1

u/techforallseasons 28d ago

Depends on the engine - but most engines treat adding a NULL with the rest of a set as a NULL solution. How do you add an "UNKNOWN".

SUM( col ) is the same as 3 + 4 + 7 + NULL + 14 = NULL.

Which is pretty much why we have COALESCE() / ISNULL() / NVL() in the first place.

3

u/fauxmosexual NOLOCK is the secret magic go-faster command 28d ago

No this isn't correct, the ansi standard for SUM is to ignore null. SUM is not equivalent to adding.

What you've said is correct for addition, but SUM explicitly handles nulls.

-1

u/Reasonable_Fishing71 28d ago

Use having as a qualifier instead of where for the refund status. It won't mess with the structure of your table. (A little less efficient but the doesn't look like your query is in danger of large quantity issues). Also start with an inner join if you want to make sure an order id exists.

I'd also check your refund table to ensure there's only one line per order. If there's duplicates that'll throw you off as well

2

u/BiteCode_Dev 28d ago

Checking for multiple refund rows is a good instinct. One thing to trace before moving the condition to HAVING: the query groups by region, so HAVING keeps or removes a whole region, not an individual order. If one region has both a normal order and an order with an approved refund, which should survive? Try deciding eligibility per order before summing; the correlated NOT EXISTS example above is useful for that.

-4

u/TravelingSpermBanker 28d ago

I scratch write queries 10x that length and you need help with not completing a math operation?