Why it happens: the subquery returns too many rows
WITH customers(id, city) AS (
VALUES (1, 'London'),
(2, 'Leeds'),
(3, 'London')
)
SELECT id, city
FROM customers
WHERE city = (
SELECT city
FROM customers
WHERE id IN (1, 2)
);The inner subquery returns two rows: London and Leeds. The operator = needs a single value to compare against. In PostgreSQL and SQL Server, this form raises a cardinality error.
How to fix it in SQL
Fix 1: use IN when you mean “any of these values”
WITH customers(id, city) AS (
VALUES (1, 'London'),
(2, 'Leeds'),
(3, 'London')
)
SELECT id, city
FROM customers
WHERE city IN (
SELECT city
FROM customers
WHERE id IN (1, 2)
)
ORDER BY id;| id | city |
|---|---|
| 1 | London |
| 2 | Leeds |
| 3 | London |
Fix 2: prove uniqueness if you really need one value
If the business rule says the inner query identifies exactly one row, express that with a key or condition that guarantees it. For example, WHERE id = 1 can return a single row when id is a unique key.
Do not use LIMIT 1 as a quick patch. Picking an arbitrary row hides the fact that the original query never said which of several rows was the right one. Only limit to one row when there is an explicit rule and, if order matters, an ORDER BY that makes the result deterministic.
How to check it
Run the inner SELECT on its own and count the rows. Also test the case where it finds none.
How to avoid it next time
LIMIT 1 without a selection rule can hide a data problem.
Related cases worth checking
SQLite defines the value of a scalar subquery as the first row returned and uses NULL when there are no rows. So a query that fails in PostgreSQL or SQL Server can run in SQLite and silently pick one row. For portability, do not rely on that behaviour: make it clear whether you expect exactly one row or a set.