Why it happens: the subquery returns too many columns
The subquery below finds exactly customer 1. The problem is not the number of rows: it returns city and active when the outer expression is only comparing city.
WITH customers(id, name, city, active) AS (
VALUES (1, 'Amy', 'London', 1),
(2, 'Liam', 'London', 1),
(3, 'Megan', 'Leeds', 1),
(4, 'Peter', 'London', 0)
)
SELECT id, name
FROM customers
WHERE city = (
SELECT city, active
FROM customers
WHERE id = 1
);In a local test with SQLite, this form fails with row value misused. In PostgreSQL and MySQL, the equivalent message says a subquery used as a value cannot return more than one column.
How to fix it in SQL
Fix 1: select only the column the comparison needs
If the question is “which customers live in the same city as customer 1?”, the subquery should return only city.
WITH customers(id, name, city, active) AS (
VALUES (1, 'Amy', 'London', 1),
(2, 'Liam', 'London', 1),
(3, 'Megan', 'Leeds', 1),
(4, 'Peter', 'London', 0)
)
SELECT id, name
FROM customers
WHERE city = (
SELECT city
FROM customers
WHERE id = 1
)
ORDER BY id;| id | name |
|---|---|
| 1 | Amy |
| 2 | Liam |
| 4 | Peter |
Fix 2: if you really need to compare several columns, say so
Sometimes both columns really are part of the question. For example: “which customers have the same city and the same active flag as customer 1?”. Instead of trying to squeeze two columns into a scalar, a clear and portable option is to correlate them with EXISTS.
WITH customers(id, name, city, active) AS (
VALUES (1, 'Amy', 'London', 1),
(2, 'Liam', 'London', 1),
(3, 'Megan', 'Leeds', 1),
(4, 'Peter', 'London', 0)
)
SELECT c.id, c.name
FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM customers AS ref
WHERE ref.id = 1
AND ref.city = c.city
AND ref.active = c.active
)
ORDER BY c.id;| id | name |
|---|---|
| 1 | Amy |
| 2 | Liam |
Some engines support row value comparisons. PostgreSQL, MySQL and SQLite have syntax for comparing tuples or rows in certain contexts. Do not confuse it with a scalar subquery: if you write a scalar value on the left, the subquery on the right must be scalar too.
How to check it
Run the subquery on its own and confirm how many columns and rows it returns.
How to avoid it next time
EXISTS checks for rows; a scalar comparison needs one column.
Related cases worth checking
EXISTS does not use the selected values: it only checks whether the subquery returns any row. That is why you may see SELECT * or a list of columns inside EXISTS without that meaning a scalar subquery accepts several columns. The question is different: whether rows exist, not what a value is.