← Back to SQL, page 17

sql-0336 · Easy fresher

Customer balances show NULL for customers who have never paid. Fix the query.

SUM over no rows returns NULL, and any arithmetic with NULL is NULL, so invoice minus payments becomes NULL for customers without payments. Wrap each SUM in COALESCE(..., 0).

Full answer
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, name TEXT, invoiced INTEGER);
CREATE TABLE payments (account_id INTEGER, amount INTEGER);
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
INSERT INTO payments VALUES (1, 30), (1, 20);

The query as written:

sql
SELECT name, invoiced - (SELECT SUM(amount) FROM payments p WHERE p.account_id = a.id) AS balance
FROM accounts a ORDER BY id;
namebalance
Ana50
BilalNULL

Ana's payments sum to 50, so her balance is 50. Bilal has no payments; the subquery's SUM is NULL and the subtraction propagates it, which a report reads as 'unknown' rather than 'owes 50'.

A corrected version:

sql
SELECT name, invoiced - COALESCE((SELECT SUM(amount) FROM payments p WHERE p.account_id = a.id), 0) AS balance
FROM accounts a ORDER BY id;
namebalance
Ana50
Bilal50

COALESCE replaces the missing total with 0, so Bilal's balance is 50 as well. Totals computed over joins have the same problem and the same fix; apply it to each side that may have no rows.

sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, name TEXT, invoiced INTEGER);
CREATE TABLE payments (account_id INTEGER, amount INTEGER);
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
INSERT INTO payments VALUES (1, 30), (1, 20);

SELECT name, invoiced - (SELECT SUM(amount) FROM payments p WHERE p.account_id = a.id) AS balance
FROM accounts a ORDER BY id;

SELECT name, invoiced - COALESCE((SELECT SUM(amount) FROM payments p WHERE p.account_id = a.id), 0) AS balance
FROM accounts a ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • SUM of no rows is NULL
  • NULL in arithmetic gives NULL
  • COALESCE the aggregate, not the final expression only

Common mistakes

  • Using COUNT logic to assume SUM returns 0
  • COALESCE on the whole result, which hides real NULL invoices

Follow-ups

  • When is NULL the correct answer here?
  • How would you compute balances with a join instead?

Tips

  • Say why SUM returns NULL