Finding the second highest salary SQL - mysql

Input: Salary: 200, 300, 100 with respected id 1, 2, 3
Output: 200 [Here 200 is the closest value of the 300]
I have tried in this way:
select
Case
When (salary < (select max(salary) from Employee))
then salary
Else
NULL
end as SecondHighestSalary
from Employee
where salary < (select max(salary) from Employee)
order by salary desc limit 1;
After running this query it returns the output as expected for some conditions. Like if input is salary: 100 with the respected id 1 then my query returns only empty value But it should return the null value.
If you can complete the query or suggest how to complete then you are most welcome.

General solution:
SELECT salary
FROM employee
WHERE salary < ( SELECT MAX(salary)
FROM employee )
ORDER BY salary DESC LIMIT 1
Solution appicable to MySQL 8+:
WITH
cte AS (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) drnk
FROM employee
)
SELECT DISTINCT salary
FROM cte
WHERE drnk = 2

You could use this query this way.
SELECT salary FROM Employee ORDER BY salary DESC LIMIT 1,1
This query will fetch second most big salary.
This would work!

select salary from Employee order by salary desc limit 1 offset 1;
This should retrieve the second highest salary. It orders the salaries in descinding order, then neglect the first result by offset 1, then limit 1 limits the result to one record.

Related

MYSQL get all user rows having second max salary

I found many questions for finding - second max salary for employees. But in all these posts, only salary is selecting.
select max(salary) from user
WHERE salary NOT IN (SELECT max(salary) from user)
I need all users rows having second max salary.
sample user table
id name salary
------------------------------------
1 A 100
2 B 200
3 C 50
4 D 200
5 E 100
and my expected result is,
id name salary
------------------------------------
1 A 100
5 E 100
You could use two subqueries to isolate the second highest salary, e.g.
SELECT id, name, salary
FROM user
WHERE salary = (SELECT MAX(salary) FROM user WHERE salary < (SELECT MAX(salary) FROM user));
Demo
Note that if you are using MySQL 8+, and are open to using analytic functions, then DENSE_RANK really helps here:
WITH cte AS (
SELECT id, name, salary, DENSE_RANK() OVER (ORDER BY salary DESC) dr
FROM user
)
SELECT id, name, salary
FROM cte
WHERE dr = 2;
You can do like below
SELECT *
FROM user
WHERE salary = (SELECT salary
FROM user
GROUP BY salary
ORDER BY salary DESC
LIMIT 1, 1)
you will get 2nd max salary by this query
SELECT salary FROM user ORDER BY salary DESC LIMIT 1, 1;

MySQL Query To Find The Second Maximum Salary explanation required

can anyone explain how below query is working?
what concept is this?
SELECT salary FROM (SELECT salary FROM employees ORDER BY salary DESC LIMIT 2) AS Emp
ORDER BY salary LIMIT 1;
SELECT salary FROM employees ORDER BY salary DESC LIMIT 2
your 1st/sub-query query returned 2 salary of the salary column(as you said limit 2), as you ordered it on descending order thats why it will return last 2 big salary
Then the 2nd query/main query will pick one among the returned 2 row of 1st query and it will returned the minimum from the 2 salary because it is by default ordered on ascending order
SELECT salary FROM
(SELECT salary FROM employees ORDER BY salary DESC LIMIT 2)
AS Emp ORDER BY salary LIMIT 1;
For example: salary column have 10,20,30,35 records
and
main query
SELECT salary FROM employees ORDER BY salary DESC LIMIT 2--then
output of this 35 and 30
Then main
SELECT salary FROM
(SELECT salary FROM employees ORDER BY salary DESC LIMIT 2)
AS Emp ORDER BY salary LIMIT 1; -- it will return 30 from the upper result set

How to find second highest salary in mysql

How to find second highest salary in mysql.
All record find in second highest salary.
Table : Employee
ID salary emp_name
1 400 A
2 800 B
3 300 C
4 400 D
4 400 C
*** Mysql Query: ***
SELECT * FROM employee ORDER by salary DESC LIMIT 1,2
This return two record.I do not know how many record in second highest salary.
Try this:
SELECT emp_name,salary
FROM Employee
WHERE salary = (SELECT DISTINCT salary FROM Employee as emp1
WHERE (SELECT COUNT(DISTINCT salary)=2 FROM Employee as emp2
WHERE emp1.salary <= emp2.salary))
ORDER BY emp_name
SELECT sal
FROM emp
ORDER BY sal DESC
LIMIT 1, 1;
You will get only the second max salary.
And if you need any 3rd or 4th or Nth value you can increase the first value followed by LIMIT (n-1) ie. for 4th salary: LIMIT 3, 1;
1st one with limit-
SELECT SALARY FROM tbl_name ORDER BY SALARY DESC LIMIT 1,1
2nd one without limit-
SELECT MAX(SALARY) FROM tbl_name WHERE SALARY < (SELECT MAX(SALARY) FROM tbl_name)
SELECT * FROM employee GROUP BY salary ORDER BY salary DESC LIMIT 1, 1
Above query first grouped salary column (for distinct record) and display records in descending order then apply limit function (limit function accept two parameter first one is for index(which is start from 0) and second one is for how many record we want).
If you want third highest salary just change limit 2,1 and so on for next.
Use this to find 2nd highest salary.
SELECT * FROM tablename ORDER BY salary DESC LIMIT 1,1
first 1 in limit is to skipping the rows and second 1 in limit is to display the row.
For third highest skip two rows same scenario to find nth salaries of the employees.
SELECT * FROM tablename ORDER BY salary DESC LIMIT 2,1
select salary
from (
select salary
from Employee
order by desc
limit 2) as minimumTwoSalary
order by minimumTwoSalary.salary
limit 1;
Using GROUP BY with ORDER BY will give you the second highest salary even if there is two same salary
SELECT * FROM employee GROUP BY salary ORDER by salary DESC LIMIT 1,1
Try this:
SELECT MAX(SALARY)
FROM tbl_name
WHERE
SALARY NOT IN
(
SELECT MAX(SALARY)
FROM tbl_name
)
Use the below query to get the 2nd or nth highest salary. Basically, The DENSE_RANK()
assigns a rank to each row within a partition or result set with no gaps in ranking values.
The rank of a row is increased by one from the number of distinct rank values which come before the row.
SELECT salary as highest_salary FROM
(SELECT salary, DENSE_RANK() OVER( ORDER BY salary DESC) row_num FROM Employee) with_dense_rank
WHERE row_num = 2;
select max(salary) from Employee where salary != (select max(salary) from Employee)
Explanation: -
In the above query, we are using the max function of SQL to find the maximum salary then we are comparing max salary using where clause with the help of subquery to filter out the maximum salary from the salary column.
Another example of the same approach is below. I believe it is the easiest logical method but maybe not the fastest because the subquery makes the output a bit slower.
select max(salary) from Employee where salary < (select max(salary) from Employee)
So, I will go with #Renuka Kulkarni Approach, but just a little different in the query, because some employees can also have the same amount of salary. so we need to select Distinct, it is important to use distinct because maybe 2 and multiple employees can have the same amount of salary.
SELECT DISTINCT price
FROM Product
ORDER BY price DESC
LIMIT 1, 1;
We can find Second Highest Salary in many ways.
1.Normal Where Condition Using MAX() Function
SELECT MAX(salary) AS SecondHighestSalary
FROM Employee WHERE salary<(SELECT MAX(salary) FROM Employee);
2.Using LIMIT
SELECT salary AS SecondHighestSalary FROM Employee ORDER BY salary DESC
LIMIT 1,1;
3.Using Self JOIN
SELECT MAX(e2.salary) AS SecondHighestSalary
FROM Employee e1, Employee e2 WHERE e1.salary>e2.salary;
4.Using NOT IN Keyword
SELECT MAX(salary) AS SecondHighestSalary
FROM Employee
WHERE salary NOT IN (SELECT MAX(salary) FROM Employee);
SELECT * FROM employee ORDER by salary DESC LIMIT 1,1;

Find max and second max salary for a employee table MySQL

Suppose that you are given the following simple database table called Employee that has 2 columns named Employee ID and Salary:
Employee
Employee ID Salary
3 200
4 800
7 450
I wish to write a query select max(salary) as max_salary, 2nd_max_salary from employee
then it should return
max_salary 2nd_max_salary
800 450
i know how to find 2nd highest salary
SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )
or to find the nth
SELECT FROM Employee Emp1 WHERE (N-1) = ( SELECT COUNT(DISTINCT(Emp2.Salary)) FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)
but i am unable to figureout how to join these 2 results for the desired result
You can just run 2 queries as inner queries to return 2 columns:
select
(SELECT MAX(Salary) FROM Employee) maxsalary,
(SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )) as [2nd_max_salary]
SQL Fiddle Demo
Try like this
SELECT (select max(Salary) from Employee) as MAXinmum),(max(salary) FROM Employee WHERE salary NOT IN (SELECT max(salary)) FROM Employee);
(Or)
Try this, n would be the nth item you would want to return
SELECT DISTINCT(Salary) FROM table ORDER BY Salary DESC LIMIT n,1
In your case
SELECT DISTINCT(column_name) FROM table_name ORDER BY column_name DESC limit 2,1;
Simplest way to fetch second max salary & nth salary
select
DISTINCT(salary)
from employee
order by salary desc
limit 1,1
Note:
limit 0,1 - Top max salary
limit 1,1 - Second max salary
limit 2,1 - Third max salary
limit 3,1 - Fourth max salary
The Best & Easiest solution:-
SELECT
max(salary)
FROM
salary
WHERE
salary < (
SELECT
max(salary)
FROM
salary
);
You can write 2 subqueries like this example
SELECT (select max(Salary) from Employee) as max_id,
(select Salary from Employee order by Salary desc limit 1,1) as max_2nd
Select Distinct sal From emp Order By sal Desc Limit 1,1;
It will take all Distinct sal. And Limit 1,1 means: leaves top one record and print 1 record.
$q="select * from info order by salary desc limit 1,0"; // display highest 2 salary
or
$q="select * from info order by salary desc limit 1,0"; // display 2nd highest salary
I think, It is the simplest way to find MAX and second MAX Salary.You may try this way.
SELECT MAX(Salary) FROM Employee; -- For Maximum Salary.
SELECT MAX(Salary) FROM Employee WHERE Salary < (SELECT MAX(Salary) FROM Employee); -- For Second Maximum Salary
i think that the simple way in oracle is this:
SELECT Salary FROM
(SELECT DISTINCT Salary FROM Employee ORDER BY Salary desc)
WHERE ROWNUM <= 2;
`select max(salary) as first, (select salary from employee order by salary desc limit 1, 1) as second from employee limit 1`
For max salary simply we can use max function, but second max salary we should use sub query. in sub query we can use where condition to check second max salary or simply we can use limit.
You can write SQL query in any of your favorite database e.g. MySQL, Microsoft SQL Server or Oracle. You can also use database specific feature e.g. TOP, LIMIT or ROW_NUMBER to write SQL query, but you must also provide a generic solution which should work on all database. In fact, there are several ways to find second highest salary and you must know a couple of them e.g. in MySQL without using the LIMIT keyword, in SQL Server without using TOP and in Oracle without using RANK and ROWNUM.
Generic SQL query:
SELECT
MAX(salary)
FROM
Employee
WHERE
Salary NOT IN (
SELECT
Max(Salary)
FROM
Employee
);
Another solution which uses sub query instead of NOT IN clause. It uses < operator.
SELECT
MAX(Salary)
FROM
Employee
WHERE
Salary < (
SELECT
Max(Salary)
FROM
Employee
);
This solution will give all employee name and salary who have second highest salary
SELECT name, salary
FROM employee
WHERE salary = (
SELECT
salary
FROM employee AS emp
ORDER BY salary DESC
LIMIT 1,1
);
Find Max salary of an employee
SELECT MAX(Salary) FROM Employee
Find Second Highest Salary
SELECT MAX(Salary) FROM Employee
Where Salary Not In (Select MAX(Salary) FROM Employee)
OR
SELECT MAX(Salary) FROM Employee
WHERE Salary <> (SELECT MAX(Salary) FROM Employee )
This will be the simplest code format :
select max(salary) as 'max_salary',
(select salary from employee order by salary desc limit 1,1) as
'2nd_max_salary'
from employee;
For finding the nth highest salary, syntax is :
select max(salary) as 'max_salary',
(select salary from employee order by salary desc limit n-1,1) as
'nth_max_salary'
from employee;
Not really a nice query but :
SELECT * from (
SELECT max(Salary) from Employee
) as a
LEFT OUTER JOIN
(SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )) as b
ON 1=1
For unique salaries (i.e. first can't be same as second):
SELECT
MAX( s.salary ) AS max_salary,
(SELECT
MAX( salary )
FROM salaries
WHERE salary <> MAX( s.salary )
ORDER BY salary DESC
LIMIT 1
) AS 2nd_max_salary
FROM salaries s
And also because it's such an unnecessary way to go about solving this problem (Can anyone say 2 rows instead of 2 columns, LOL?)
Try
SELECT
SUBSTRING( GROUP_CONCAT( Salary ), 1 , LOCATE(",", GROUP_CONCAT( Salary ) ) -1 ) AS max_salary,
SUBSTRING( GROUP_CONCAT( Salary ), LOCATE(",", GROUP_CONCAT( Salary ) ) +1 ) AS second_max_salary
FROM
(
SELECT Salary FROM `Employee` ORDER BY Salary DESC LIMIT 0,2
) a
Demo here
For second highest salary, This one work for me:
SELECT salary
FROM employee
WHERE salary
NOT IN (
SELECT MAX( salary )
FROM employee
ORDER BY salary DESC
)
LIMIT 1
This is awesome Query to find the nth Maximum:
For example: -
You want to find salary 8th row Salary, Just Changed the indexed value to 8.
Suppose you have 100 rows with Salary. Now you want to find Max salary for 90th row. Just changed the Indexed Value to 90.
set #n:=0;
select * from (select *, (#n:=#n+1) as indexed from employee order by Salary desc)t where t.indexed = 1;
with Common table expression
With cte as (
SELECT
ROW_NUMBER() Over (Order By Salary Desc) RowNumber,
Max(Salary) Salary
FROM
Employee
Group By Salary
)
Select * from cte where RowNumber = 2
without nested query
select max(e.salary) as max_salary, max(e1.salary) as 2nd_max_salary
from employee as e
left join employee as e1 on e.salary != e1.salary
group by e.salary desc limit 1;
Here change n value according your requirement:
SELECT top 1 amount
FROM (
SELECT DISTINCT top n amount
FROM payment
ORDER BY amount DESC ) AS temp
ORDER BY amount
This should work same :
SELECT MAX(salary) max_salary,
(SELECT MAX(salary)
FROM Employee
WHERE salary NOT IN
(SELECT MAX(salary)
FROM Employee)) 2nd_max_salary
FROM Employee
If we want to find Employee that gets 3nd highest salary then execute this query
SELECT a.employeeid,
a.salary
FROM (SELECT employeeid,
salary,
Dense_rank()
OVER(
ORDER BY salary) AS n
FROM employee) AS a
WHERE n = 3
What do you want
This will work To find the nth maximum number
SELECT
TOP 1 * from (SELECT TOP nth_largest_no * FROM Products Order by price desc) ORDER BY price asc;
For Fifth Largest number
SELECT
TOP 1 * from (SELECT TOP 5 * FROM Products Order by price desc) ORDER BY price asc;
Here is another solution which uses sub query but instead of IN clause it uses < operator
SELECT MAX(Salary) From Employees WHERE Salary < ( SELECT Max(Salary) FROM Employees);
select * from emp where sal =(select max(sal) from emp where eno in(select eno from emp where sal <(select max(sal)from emp )));
try the above code ....
if you want the third max record then add another nested query "select max(sal)from emp" inside the bracket of the last query and give less than operator in front of it.
select * from
Employees where Sal >=
(SELECT
max(Sal)
FROM
Employees
WHERE
Sal < (
SELECT
max(Sal)
FROM
Employees;
));
Max Salary:
select max(salary) from tbl_employee <br><br>
Second Max Salary:
select max(salary) from tbl_employee where salary < ( select max(salary) from tbl_employee);
Try below Query, was working for me to find Nth highest number salary.
Just replace your number with nth_No
Select DISTINCT TOP 1 salary
from
(Select DISTINCT TOP *nth_No* salary
from Employee
ORDER BY Salary DESC)
Result
ORDER BY Salary

Get the second highest value in a MySQL table

I have a table of employees and salaries defined that way:
"name" (type: VARCHAR)
"salary" (type: INTEGER)
What query can I use to get the second highest salary in this table?
Here's one that accounts for ties.
Name Salary
Jim 6
Foo 5
Bar 5
Steve 4
SELECT name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees))
Result --> Bar 5, Foo 5
EDIT:
I took Manoj's second post, tweaked it, and made it a little more human readable. To me n-1 is not intuitive; however, using the value I want, 2=2nd, 3=3rd, etc. is.
/* looking for 2nd highest salary -- notice the '=2' */
SELECT name,salary FROM employees
WHERE salary = (SELECT DISTINCT(salary) FROM employees as e1
WHERE (SELECT COUNT(DISTINCT(salary))=2 FROM employees as e2
WHERE e1.salary <= e2.salary)) ORDER BY name
Result --> Bar 5, Foo 5
A straight forward answer for second highest salary
SELECT name, salary
FROM employees ORDER BY `employees`.`salary` DESC LIMIT 1 , 1
another interesting solution
SELECT salary
FROM emp
WHERE salary = (SELECT DISTINCT(salary)
FROM emp as e1
WHERE (n) = (SELECT COUNT(DISTINCT(salary))
FROM emp as e2
WHERE e1.salary <= e2.salary))
Seems I'm much late to answer this question. How about this one liner to get the same output?
SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1,1 ;
sample fiddle: https://www.db-fiddle.com/f/v4gZUMFbuYorB27AH9yBKy/0
create table svalue (
name varchar(5),
value int
) engine = myisam;
insert into svalue value ('aaa',30),('bbb',10),('ccc',30),('ddd',20);
select * from svalue where value = (
select value
from svalue
group by value
order by value desc limit 1,1)
FOR SECOND LAST:
SELECT name, salary
FROM employee
ORDER BY salary DESC
LIMIT 1 , 1
FOR THIRD LAST:
SELECT name, salary
FROM employee
ORDER BY salary DESC
LIMIT 2 , 1
You can use this below mentioned query
SELECT emp.name, emp.salary
FROM employees emp
WHERE 2 = (SELECT COUNT(DISTINCT salary)
FROM employees
WHERE emp.salary<=salary
);
You can change 2 to your desired highest record.
To display records having second largest value of mark:
SELECT username, mark
FROM tbl_one
WHERE mark = (
SELECT DISTINCT mark
FROM tbl_one
ORDER by mark desc
LIMIT 1,1
);
simple solution
SELECT * FROM TBLNAME ORDER BY COLNAME ASC LIMIT (n - x), 1
Note: n = total number of records in column
x = value 2nd, 3rd, 4th highest etc
e.g
//to find employee with 7th highest salary
n = 100
x = 7
SELECT * FROM tbl_employee ORDER BY salary ASC LIMIT 93, 1
hope this helps
Found another interesting solution
SELECT salary
FROM emp
WHERE salary = (SELECT DISTINCT(salary)
FROM emp as e1
WHERE (n) = (SELECT COUNT(DISTINCT(salary))
FROM emp as e2
WHERE e1.salary <= e2.salary))
Sorry. Forgot to write. n is the nth number of salary which you want.
The simple solution is as given below in query:
select max(salary) as salary from employees where salary<(select max(salary) from employees);
for 2nd heightest salary
select max(salary) from salary where salary not in (select top 1 salary from salary order by salary desc)
for 3rd heightest salary
select max(salary) from salary where salary not in (select top 2 salary from salary order by salary desc)
and so on......
SELECT MAX(salary) salary
FROM tbl
WHERE salary <
(SELECT MAX(salary)
FROM tbl);
To get the *N*th highest value, better to use this solution:
SELECT * FROM `employees` WHERE salary =
(SELECT DISTINCT(salary) FROM `employees`
ORDER BY salary DESC LIMIT {N-1},1);
or you can try with:
SELECT * FROM `employees` e1 WHERE
(N-1) = (SELECT COUNT(DISTINCT(salary))
FROM `employees` e2
WHERE e1.salary < e2.salary );
N=2 for second highest
N=3 for third highest and so on.
SELECT DISTINCT Salary
FROM emp
ORDER BY salary DESC
LIMIT 1 , 1
This query will give second highest salary of the duplicate records as well.
To get the second highest salary just use the below query
SELECT salary FROM employees
ORDER BY salary DESC LIMIT 1,1;
To get second highest value:
SELECT `salary` FROM `employees` ORDER BY `salary` DESC LIMIT 1, 1;
SELECT name, salary
FROM employees
where
salary = (SELECT (salary) FROM employees GROUP BY salary DESC LIMIT 1,1)
Try this one to get n th max salary
i have tried this before posting & It Works fine
eg. to find 10th max salary replace limit 9,1;
mysql> select name,salary from emp group by salary desc limit n-1,1;
SELECT MIN(id) as id FROM students where id>(SELECT MIN(id) FROM students);
SELECT name, salary
FROM EMPLOYEES
WHERE salary = (
SELECT DISTINCT salary
FROM EMPLOYEES
ORDER BY salary DESC
LIMIT 1 , 1 )
with alias as
(
select name,salary,row_number() over(order by salary desc ) as rn from employees
)
select name,salary from alias where rn=n--n being the nth highest salary
SELECT username, salary
FROM tblname
GROUP by salary
ORDER by salary desc
LIMIT 0,1 ;
SELECT name,salary FROM employee
WHERE salary = (SELECT DISTINCT(salary) FROM employee ORDER BY salary DESC LIMIT 1,1) ORDER BY name
Get second, third, fourth......Nth highest salary using following query
SELECT MIN(salary) from employees WHERE salary IN( SELECT TOP N salary FROM employees ORDER BY salary DESC)
Replace N by you number i.e. N=2 for second highest salary,
N=3 for third highest salary and so on. So for second highest salary use
SELECT MIN(salary) from employees WHERE salary IN( SELECT TOP 2 salary FROM employees ORDER BY salary DESC)
SELECT name, salary
FROM employees
order by salary desc limit 1,1
and this query should do your job.
First we are sorting the table in descending way so the person with the highest salary is at the top, and the second highest is at the second position. Now limit a,b means skip the starting a elements and then print the next b elements. So you should use limit 1,1 in this case.
Hope this helps.
Try this :
SELECT DISTINCT(`salary`)
FROM `employee`
ORDER BY `salary` DEC
LIMIT 1,1
SELECT SALARY
FROM (SELECT *
FROM EMPLOYEE
ORDER BY SALARY
DESC LIMIT ***2***) AS TOP_SALARY
ORDER BY SALARY ASC
LIMIT 1
select MIN(salary) from employee order by age desc limit 2;
It sorts the column in descending order takes the top 2 and returns the minimum of them which is the second highest.
Try this :
Proc sql;
select employee, salary
from (select * from test having salary < max(salary))
having salary = max(salary)
;
Quit;