Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solution to "subquery returns more than 1 row" error

Tags:

mysql

I have one query that returns multiple rows, and another query in which I want to set criteria to be either one of values from those multiple rows , so basicly I want the subquery to look something like this:

select * 
from table
where id= (multiple row query);

Where multiple row query returns multiple rows. So if the values from those rows are 1,2,3 then I want to set id to be 1 or 2 or 3.

like image 280
wdc Avatar asked Jan 27 '15 13:01

wdc


People also ask

How do I fix single row subquery returns more than one row?

There are essentially two options to take. The first is to rewrite the query so that the subquery will only return a single row, thus eliminating the source of the error. This will require a user to rethink how they wish to acquire the data that they were initially searching for.

What would happen if more than one rows are returned from subquery?

Multiple-row subqueries are nested queries that can return more than one row of results to the parent query. Multiple-row subqueries are used most commonly in WHERE and HAVING clauses. Since it returns multiple rows, it must be handled by set comparison operators (IN, ALL, ANY).

How do you avoid subquery returned more than 1 value this is not permitted?

This is not permitted when the subquery follows =, != , <, <= , >, >= or when the subquery is used as an expression.


3 Answers

= can be used when the subquery returns only 1 value.

When subquery returns more than 1 value, you will have to use IN:

select * 
from table
where id IN (multiple row query);

For example:

SELECT *
FROM Students
WHERE Marks = (SELECT MAX(Marks) FROM Students)   --Subquery returns only 1 value

SELECT *
FROM Students
WHERE Marks IN 
      (SELECT Marks 
       FROM Students 
       ORDER BY Marks DESC
       LIMIT 10)                       --Subquery returns 10 values
like image 166
Raging Bull Avatar answered Oct 17 '22 12:10

Raging Bull


You can use in():

select * 
from table
where id in (multiple row query)

or use a join:

select distinct t.* 
from source_of_id_table s
join table t on t.id = s.t_id
where <conditions for source_of_id_table>

The join is never a worse choice for performance, and depending on the exact situation and the database you're using, can give much better performance.

like image 23
Bohemian Avatar answered Oct 17 '22 13:10

Bohemian


Use MAX in your SELECT query to return one value… EXAMPLE

INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT MAX(student_id) FROM student), (SELECT MAX(syr_id) FROM school_year))

instead of

INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT (student_id) FROM student), (SELECT (syr_id) FROM school_year))

try it without MAX it will return more than one value

like image 2
John Nico Novero Avatar answered Oct 17 '22 11:10

John Nico Novero