MySQL & MariaDB error 1242: Subquery returns more than 1 row
Subquery returns more than 1 row (5.6.51) A subquery used as a single value (in a SELECT list, or with =, <, >) returned several rows, so the server can't tell which one you mean.
| MySQL | MariaDB | |
|---|---|---|
| Symbol | ER_SUBQUERY_NO_1_ROW | ER_SUBQUERY_NO_1_ROW |
| SQLSTATE | 21000 | 21000 |
| Type | Server error | Server error |
| Versions | every release since 5.0 active | every release since 5.5 active |
What it means
A scalar subquery must return at most one row and one column. SELECT id, (SELECT boss FROM dept WHERE dept.name = emp.dept) … works until one department has two bosses; then the statement fails for the whole query, not just that row.
Why it happens
- The data changed: a lookup that “always” matched one row now matches two (duplicate rows, missing unique key).
WHERE col = (SELECT …)whereIN (SELECT …)was meant.- A correlated subquery missing part of its join condition.
How to fix it
- If several rows are valid, use
IN,EXISTSor a JOIN instead of=. - If you want one specific row, say which:
ORDER BY … LIMIT 1, or an aggregate (MIN(),MAX(),GROUP_CONCAT()). - If only one row should ever match, add a UNIQUE key to enforce it, and find the duplicates with
GROUP BY … HAVING COUNT(*) > 1.
Reproduce it yourself
These steps are the exact test our harness runs. Use a scratch server, never production.
Connect with
mysql -u root -pand create a scratch database and the test data:CREATE DATABASE demo; USE demo; CREATE TABLE emp (id INT, dept VARCHAR(10)); CREATE TABLE dept (name VARCHAR(10), boss VARCHAR(10)); INSERT INTO emp VALUES (1,'it'); INSERT INTO dept VALUES ('it','ann'),('it','bob');Run:
SELECT id, (SELECT boss FROM dept WHERE dept.name = emp.dept) AS boss FROM emp;
You get: Subquery returns more than 1 row(11.8.9)
Verified fixes
Decide which row you want (LIMIT 1 with ORDER BY, an aggregate) or use IN / JOIN
SELECT id, (SELECT MIN(boss) FROM dept WHERE dept.name = emp.dept) AS boss FROM emp;
Tested on
| Step | MySQL | MariaDB | |||||||
|---|---|---|---|---|---|---|---|---|---|
| 5.6 | 5.7 | 8.0 | 8.4 | 9 | 10.6 | 10.11 | 11.4 | 11.8 | |
| A scalar subquery (used as a value) finds two rows repro | ✓ 1242 | ✓ 1242 | ✓ 1242 | ✓ 1242 | ✓ 1242 | ✓ 1242 | ✓ 1242 | ✓ 1242 | ✓ 1242 |
| Decide which row you want (LIMIT 1 with ORDER BY, an aggregate) or use IN / JOIN fix | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |