SQL Queries That Will Surprise You! 🚀💡
SQL is the backbone of data manipulation, but some queries are not your everyday SELECT *
. 🤯 Whether you’re a beginner or a seasoned developer, these mind-bending SQL queries will leave you astonished. Let’s dive in! 🌊
1. Finding the Second Highest Salary 🏆
Have you ever struggled to find the runner-up salary in a table? Here’s how to do it without using LIMIT
or OFFSET
:
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
Explanation:
- The inner query finds the highest salary.
- The outer query finds the maximum salary that is less than the highest.
2. Detecting Missing Gaps in a Sequence 🔍
To find missing IDs in a sequence:
SELECT t1.id + 1 AS missing_id
FROM table_name t1
LEFT JOIN table_name t2
ON t1.id + 1 = t2.id
WHERE t2.id IS NULL;
Explanation:
- Join each row to the next expected row.
- Filter out rows where the next ID exists.
3. Finding the Nth Highest Value 🥉
If you need the nth highest value, here’s a general approach:
SELECT DISTINCT…