Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

PostgreSQL Subquery: Get three maximum salaries


19. Write a query to get three maximum salaries.

Sample Solution:

Code:

SELECT DISTINCT salary 
FROM employees a 
WHERE  3 >= (SELECT COUNT(DISTINCT salary) 
FROM employees b 
WHERE a.salary <= b.salary) 
ORDER BY a.salary DESC;

Sample table: employees


Output:

pg_exercises=# SELECT DISTINCT salary
pg_exercises-# FROM employees a
pg_exercises-# WHERE  3 >= (SELECT COUNT(DISTINCT salary)
pg_exercises(# FROM employees b
pg_exercises(# WHERE a.salary <= b.salary)
pg_exercises-# ORDER BY a.salary DESC;
  salary
----------
 24000.00
 17000.00
 14000.00
(3 rows)

Practice Online


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a subquery to display the information for all the departments where no employee is working.
Next: Write a query to get three minimum salaries.

What is the difficulty level of this exercise?