Reputation:
How to find the second largest value from two tables combined? I have written the following code but i would like something smaller and more efficient.
SELECT MAX(salary)
FROM (
SELECT salary FROM employees
UNION
SELECT salary FROM professors
) X
WHERE salary < (
SELECT MAX(salary)
FROM (
SELECT salary FROM employees
UNION
SELECT salary FROM professors
) Y
);
Upvotes: 0
Views: 159
Reputation: 6018
Depending on your DBMS, the syntax may vary slightly, but need to grab 1 row offset by 1 row.
This is probably fastest way to do it. Could also use WHERE ROW_NUMBER() = 2, but that will require scanning all your data.
SELECT *
FROM hil.employees
ORDER BY Salary DESC
OFFSET 1 ROW FETCH NEXT 1 ROW ONLY
Not sure goal of your query, but appears you might be wanting to grab the 2nd highest between the two tables. Keep in mind, your UNION removes any duplicate values, which may or may not be desirable
SELECT Salary
FROM hil.employees
UNION
SELECT Salary
FROM hil.professors
ORDER BY Salary DESC
OFFSET 1 ROW FETCH NEXT 1 ROW ONLY
Upvotes: 2