Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

296
Views
How to overcome the error Subquery returns more than 1 row in Mysql

I want to find all employee names who earn more than average salary of all employees of their company.

This is the database

create table works(
employee_name varchar (100) primary key,
company_name varchar (100),
salary int (6) );

This is the code I used,

select employee_name
from works
where salary > (select avg(salary) from works group by company_name)
group by company_name;
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Instead of a group by in the subquery, you just need a where clause:

SELECT employee_name
FROM works w
WHERE salary > (select avg(salary) from works w2 where w2.company_name = w.company_name);
over 4 years ago · Santiago Trujillo Report

0

You don't need a group by in the outer select, but you have to add a where clause to the inner select.

create table works(
employee_name varchar (100) primary key,
company_name varchar (100),
salary int (6) );
INSERT INTO works VALUES ('a','comp A',100),('a2','comp A',150),('a3','comp A',250),('a4','comp B',100)
,('a5','comp B',300),('a6','comp B',200)
select employee_name,company_name,salary
from works w1
where salary >= (select avg(salary) avgsal from works w2 WHERE w1.company_name = w2.company_name 
group by company_name
)
;
employee_name | company_name | salary
:------------ | :----------- | -----:
a3            | comp A       |    250
a5            | comp B       |    300
a6            | comp B       |    200
select avg(salary) avgsal from works w2  
group by company_name
|   avgsal |
| -------: |
| 166.6667 |
| 200.0000 |

db<>fiddle here

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!