SQL error · Subqueries and set operations

The subquery returns too many rows

Problem: A scalar comparison expects one value, but the subquery returns several.

Solution: Use IN if you are testing membership in a set; if you need a single value, guarantee uniqueness with a specific key or rule.

Why it happens: the subquery returns too many rows

Problem SQL
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.

“The subquery returns too many rows” error messages by engine

The exact wording depends on the database. Compare these common messages with the one in your console.

EngineTypical message
PostgreSQLERROR: more than one row returned by a subquery used as an expression
MySQLERROR 1242 (21000): Subquery returns more than 1 row
SQL ServerMsg 512, Level 16: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
OracleORA-01427: single-row subquery returns more than one row

SQLite raises no error: it simply uses the first row of the subquery, which can hide the problem.

How to fix it in SQL

Fix 1: use IN when you mean “any of these values”

Fixed SQL using a set
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;
Result when the goal is membership in the set of cities
idcity
1London
2Leeds
3London

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.