sqlstreak

SQL error

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

Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)

Short answer

A subquery used with = must return exactly one value, but yours returns several rows. Use IN (subquery) to match any of them, or EXISTS for a correlated check.

The exact messages

  • PostgreSQLERROR: more than one row returned by a subquery used as an expression
  • SQLiteNo error, but a silent surprise: see below.

How to read this message

This is what PostgreSQL 18.6 prints for the broken query below, the way psql shows it.

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

Why it happens

Using = where you meant IN

“Customers who placed a delivered order” matches many customers, so the subquery returns many ids.

A lookup that isn't unique

If you expect one row, the data has duplicates. Add a stricter condition, or LIMIT 1 with an ORDER BY if any one row is fine.

Reproduce it, then fix it

Both queries run on a real database in your browser. Switch dialects to compare.

Broken
SELECT name FROM customers
WHERE id = (SELECT customer_id FROM orders
            WHERE status = 'delivered');
Fixed
SELECT name FROM customers
WHERE id IN (SELECT customer_id FROM orders
             WHERE status = 'delivered');

IN accepts a list of values, so every matching customer is returned.

The fix returns, PostgreSQL: first 6 of 7 rows

name
Maya Ortiz
Jonah Reed
Tomás Herrera
Ellie Park
Sam Okafor
Lena Fischer

The fix returns, SQLite: first 6 of 7 rows

name
Maya Ortiz
Jonah Reed
Tomás Herrera
Ellie Park
Sam Okafor
Lena Fischer

Experiment with it: PostgreSQL playground·SQLite playground

What SQLite does instead

SQLite silently uses the first row the subquery returns. The query “works”, but returns only part of the answer: here one customer instead of all of them.

Official documentation

Stop hitting this error

Practise the concept behind it in a five-minute lesson, or read the full guide: SQL subqueries.