PostgreSQL error: more than one row returned by a subquery

ERROR:  more than one row returned by a subquery used as an expression

A subquery used where a single value belongs — after =, in a SELECT list, in an assignment — returned more than one row. Half the time the query is wrong (you meant a set, not a value); the other half the query is right and the data has duplicates nobody knew about.

What this error means

A scalar subquery context (WHERE x = (SELECT ...), SELECT (SELECT ...) AS y, SET col = (SELECT ...)) requires zero rows (→ NULL) or one row. Two or more is an error at execution time — which means it can lurk in production for months and fire the first day the data makes the subquery multi-row.

Common causes

How to diagnose it

-- Esegui la subquery da sola: quante righe? quali?
SELECT id FROM payments WHERE order_id = 42;

-- Se "non dovrebbero esserci duplicati", trovali:
SELECT order_id, count(*)
FROM payments
GROUP BY order_id
HAVING count(*) > 1;

How to fix it

🔍 The constraint that keeps this fixed: duplicate key value violates unique constraint.