Home > front end >  How to select name with the maximum salary in sql query
How to select name with the maximum salary in sql query

Time:10-05

How to select name with the maximum salary

Id. Name. Salary.

  1.  Kobe.    50000
    
  2.  Lebron.  500099
    
  3.  Steph.   628228
    
  4.  Thompson. 50505
    
  5.  Shabu     393828
    

CodePudding user response:

The CTE represents your table. The query you need is the last 3 lines, where it's sorting the output by salary in descending order, then limiting to 1 row.

with salaries as (
  select 1 as id, 'Kobe' as name, 50000 as salary union all
  select 2, 'Lebron', 1000000 union all
  select 3, 'Steph', 222222
  )
select name
from salaries
order by salary desc limit 1

Output:

Lebron

UPDATE

Per your comment about using a Max function, here's one way, using a sub-query:

select name
from salaries
where salary = (select max(salary) from salaries);

CodePudding user response:

Expanding on 53RT's comment, for MySQL:

SELECT Name 
FROM myTable
ORDER BY Salary DESC
LIMIT 1

CodePudding user response:

You can use a sub-query to to so

SELECT 
t.name
FROM <your_table_name> t
WHERE t.id = 
(SELECT 
t1.id 
FROM 
<your_table_name> t1
ORDER BY t1.salary
DESC LIMIT 1);

EDIT

Or you can just use

SELECT 
t1.name
FROM 
<your_table_name> t1
ORDER BY t1.salary
DESC LIMIT 1
  • Related