How to use Subquery In SQL

By using the Joins, we can use subquery for finding the nth highest salary. In our approach, we will simply find all the rows which have the salary lower than the maximum salary. From that result we will find the highest salary which will be our desired result. Here is the query for this approach.

SELECT t."Group_Id", MAX(t."Salary") AS Salary
FROM "Test" t
WHERE t."Salary" < (
SELECT MAX("Salary")
FROM "Test" t2
WHERE t2."Group_Id" = t."Group_Id"
)
GROUP BY t."Group_Id";

Output:

Group_id

salary

1

25000

2

30000

3

15000

Explanation:

We have simply find the highest salary in each group and fetch all the records which have less salary than highest salary. In other words we have removed the records which have highest salary. Now from the remaining records highest salary will be the 2nd highest salary of the overall records.

List the Second Highest Salary By Department

Listing the second-highest salary by department is a common task that explains the use of advanced PostgreSQL techniques. It offers several functions and methods to achieve this.

In this article, we will explore three approaches that help us to List the Second Highest Salary By Department with the help of examples and so on.

Similar Reads

List the Second Highest Salary By Department

Listing the second-highest salary by the department is a practical example that showcases the use of advanced SQL techniques. PostgreSQL is a powerful open-source relational database that offers below functions to List the Second Highest Salary By Department are as follows:...

1. Using Subquery

By using the Joins, we can use subquery for finding the nth highest salary. In our approach, we will simply find all the rows which have the salary lower than the maximum salary. From that result we will find the highest salary which will be our desired result. Here is the query for this approach....

2. Using DENSE_RANK() function

What is DENSE_RANK()?...

3. Using Common Table Expression (CTE)

By using Common Table Expression(CTE) we can create a temporary table and will use ROW_NUMBER() function. Result table after applying ROW_NUMBER() function will be temporary store. It will not reflet in the database. Here we are assuming that no two salary will be the same in same partition....

Conclusion

By implementing SQL queries efficiently, this task becomes manageable and provides valuable insights into departmental salary structures. Here we have retrieved our desired result using multiple methods like self join and subqueries and other is DENSE_RANK() function, Common Table Expression(CTE). DENSE_RANK() function can be used for finding nth highest salary. But for finding the nth highest salary using subquery, it will get tough when the value of n will increase. Using Common Table Expression we can create temporary table and use window functions such as ROW_NUMBER()....

Contact Us