When working with large datasets in SQL, it's not uncommon to need information beyond the highest salary. Perhaps you're curious about the second highest salary in your employees table, or you're looking to identify a specific salary bracket for recruitment purposes. Whatever your reason, SQL provides several ways to retrieve the second maximum salary.

Before we dive into the examples, let's ensure you understand our dataset. We'll be working with a table named 'employees' that has the following structure:

```sql CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(50), salary DECIMAL(10, 2) ); ```
Using Subquery with LIMIT and OFFSET
The most straightforward method to find the second highest salary is by using a subquery with the LIMIT and OFFSET clauses.

Here's an example:
```sql SELECT salary FROM ( SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 2 OFFSET 1 ) as subquery; ```
Explanation of the Subquery Approach

The subquery orders the salaries in descending order and fetches the first two distinct values using the LIMIT clause. The OFFSET clause then skips the first row, ensuring we get the second highest salary.
Do note that this method might not work as expected if there are multiple employees with the second highest salary, as it orders by salary and may skip some distinct salaries due to the LIMIT clause.
Using Self-Join

Another approach is to perform a self-join on the employees table. This method ensures that if there are multiple employees with the same second highest salary, they will all be returned.
Here's an example:
```sql SELECT e1.salary FROM employees e1 JOIN employees e2 ON e1.salary < e2.salary GROUP BY e1.salary HAVING COUNT(*) = ( SELECT COUNT(*) FROM employees WHERE salary > e1.salary ); ```
Explanation of the Self-Join Approach

The self-join compares each employee's salary with every other employee's salary. The join condition ensures that we only keep the salaries that are less than another salary. The having clause then excludes the highest salary and returns the second highest.
This method can be resource-intensive because it compares each row with every other row. However, it's the most reliable way to find the second highest salary when there could be multiple employees with the same salary.




















In practice, the choice between these methods depends on the specific requirements of your task and the size of your dataset. The subquery approach is simpler and often sufficient, while the self-join can be more reliable but may require more resources.
To explore further, consider playing with some sample data and testing both methods to see which one works best for your needs.