How to Find Second Highest Salary in SQL Server?

Updated on July 29, 2024

Article Outline

Finding the second highest salary within a SQL Server database is very common yet vital work. This query is the backbone for managing payrolls and other databases, analysing data, and preparing reports. SQL stands for Structured Query Language. It is a language that allows retrieving information stored in a database and manipulating exciting information. To understand the several ways of finding the second highest salary, we can write our queries correctly and get better practices of database handling.

A Very Brief History of SQL

SQL was developed during the mid-1970s by IBM researchers Donald D. Chamberlin and Raymond F. Boyce. It was an outgrowth of their original NATURAL-language structured query language, first offered to customers in 1974. It began under the name SEQUEL, short for Structured English Query Language. With time, SQL has grown into a crucial language regarding relational database management systems; at present, it is widely used in most fields and sectors where databases are present.

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Creating a Table in SQL Server

Before we delve deep into finding the second-highest salary, we require setting up our database. That means creating a table and filling it with some data now.

Defining the Table Structure

Let’s first create an employee table. Well, this table will have employee ID, employee name, and salary columns. Below is an example script for creating the table:

CREATE TABLE Employees ( ID INT PRIMARY KEY, Name VARCHAR(100), Salary INT );

In this script, we define a table named “Employees” with three columns:

 

  • ID: An integer that uniquely identifies each employee.
  • Name: A variable character field to store the employee’s name.
  • Salary: An integer to store the employee’s salary.

Inserting Data into the Table

Well, now we have the structure of the table. We will have to insert a few data records to make the queries and get some valuable results. Let’s now take an example of a script for inserting some employee records:

INSERT INTO Employees (ID, Name, Salary) VALUES  (1, 'Abhishek', 6000), (2, 'Babita', 7000), (3, 'Charu', 8000), (4, 'Dolly', 9000), (5, 'Elizabeth', 7500), (6, 'Farhan', 7200), (7, 'Garima', 6800), (8, 'Harsh', 7700), (9, 'Ishita', 8500), (10, 'Jagjit', 6200);

In this example, we insert five records into the Employees table. Each record includes an ID, a name, and a salary.

Ensuring Data Accuracy

It’s important to ensure the data we insert is accurate and consistent. For example, each employee should have a unique ID, and salary is an integer with positive values. Ensuring data integrity will avoid errors and produce trustworthy query results.

The Final Data Sheet

Here is the data in our Employees table:

 

ID Name Salary
1 Abhishek 6000
2 Babita 7000
3 Charu 8000
4 Dolly 9000
5 Elizabeth 7500
6 Farhan 7200
7 Garima 6800
8 Harsh 7700
9 Ishita 8500
19 Jagjit 6200

 

This data set provides a good mix of salaries, enabling us to explore various SQL queries effectively.

Viewing the Data

To check the data we’ve entered, we can use a simple SELECT query to examine all records in the Employees table:

SELECT * FROM Employees;

Running this query will display all of the employee records in the table, letting us verify that the data was accurately entered.

Methods to Find the Second Highest Salary in SQL Server

Now that our table is completed, we can proceed toward finding the second-highest salary. We can have several ways to perform this, and each of them has its benefits and different use cases.

Using the Subquery Method

One relatively simple common approach to finding the second highest salary is by using a subquery. This method refers to selecting the maximum salary that is less than the highest salary. Here is how to do it:

SELECT MAX(Salary) AS SecondHighestSalary FROM Employees WHERE Salary < (SELECT MAX(Salary) FROM Employees);

Output:

SecondHighestSalary 8500

Explanation of the above query:

 

  • The inner subquery returns the highest salary in our table, which is 9000.
  • Then, the outer query returns the maximum one less than the highest. The maximum one less than 9000 is 8500.

Using the LIMIT and OFFSET Method

Another way is to employ the LIMIT and OFFSET clauses, which are more prevalent in MySQL but may be converted for SQL Server with identical reasoning. Here’s an example:

SELECT Salary FROM ( SELECT Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS Rank FROM Employees ) AS RankedSalaries WHERE Rank = 2;

Output:

Salary 8500

This technique ranks each salary using a window function (DENSE_RANK). The outer query then chooses the salary with a rank of two, the second highest.

Implementing Common Table Expressions (CTEs) for Salary Queries

Common Table Expressions (CTEs) are a way to make a complex query easy. Using a CTE, we can break our query and easily maintain it. Here’s an example: 

WITH SalaryCTE AS ( SELECT Salary, ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNum FROM Employees ) SELECT Salary FROM SalaryCTE WHERE RowNum = 2;

Output:

Salary 8500

In the above query:

 

  • The CTE SalaryCTE assesses a row number to each salary in descending order.
  • The main query selects the salary with a row number of 2, the second highest.

Using the TOP Keyword

SQL Server provides the TOP keyword, which can be used with the DISTINCT keyword to find the second-highest salary. Here’s an example:

SELECT TOP 1 Salary FROM ( SELECT DISTINCT TOP 2 Salary FROM Employees ORDER BY Salary DESC ) AS TopSalaries ORDER BY Salary ASC;

Output:

Salary 8500

In the above query:

 

  • The inner query provides the highest two unique salaries in descending order. These are 9000 and 8500.
  • The outer query then selects the highest one among these, ordered by Salary in ascending order. This will be 8500.

Using the ROW_NUMBER() Function

Now, let’s see how we find the second-highest salary using the ROW_NUMBER() function. This function assigns a unique row number within a result set. Here is how it goes:

SELECT Salary FROM ( SELECT Salary, ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNum FROM Employees ) AS RankedSalaries WHERE RowNum = 2;

Output:

Salary 8500

In the given query:

 

  • In the inner subquery, it assigns a row number to each salary, by order in descending salary.
  • The outer query selects the salary of row number 2, which happens to be 8500.

Summary of Methods

To summarise, here are the methods we have discussed to find the second highest salary in SQL Server:

 

  1. Subquery Method: Here, nested queries are used.
  2. LIMIT and OFFSET Method: This method uses window functions to rank salaries.
  3. Common Table Expressions (CTEs): Used to break a complex query into manageable parts.
  4. TOP Keyword Method: Used by combining the TOP and DISTINCT keywords to get the desired result.
  5. ROW_NUMBER() Function Method: Used for assigning row numbers to rank salaries.

All these methods have their own pros and can be applied according to the situation. So only when we are aware of all the above techniques we can decide about the best method for applying it to our requirements.

Comparing Different Approaches for Efficiency and Simplicity

Choosing the proper method to find the second-highest salary in SQL Server depends on efficiency, simplicity, and specific use-case requirements. Now let us compare the subquery method with the other techniques :

Subquery Method

Efficiency

 

  • The subquery method is very easy to understand.
  • It gives acceptable performance for small to medium datasets.
  • The nested query might degrade performance with larger datasets.

Simplicity:

 

  • Easy to write and understand.
  • Good for small tasks and beginner SQL users.

LIMIT and OFFSET Method

Efficiency:

 

  • Highly efficient with indexed datasets.
  • Efficient for large datasets because of its ability to skip rows.
  • Performance can vary according to the SQL Server version and configuration.

Simplicity:

 

  • Slightly more complex, as it uses window functions.
  • Appropriate for users already familiar with ranking functions.

Common Table Expressions (CTEs)

Efficiency:

 

  • Clear, readable, and very flexible in writing complex queries
  • Efficiency is good because CTEs have been optimised for recursive queries or multiple references of the same subquery

Simplicity:

 

  • A bit more advanced than simple subqueries but very handy for making complex queries.
  • Best suitable for experienced users who deal with advanced SQL techniques.

TOP Keyword Method

Efficiency:

 

  • Very efficient for fetching fewer rows.
  • Can be efficient with indexed columns.
  • Best for a large data set when only a couple of the rows are required to be fetched.

Simplicity:

 

  • Easy to write and understand
  • Great for quick queries and commonly used scenarios.

ROW_NUMBER() Function Method

Efficiency:

 

  • Effective for datasets where precision in row ranking is needed.
  • Generally good in performance with indexed datasets.
  • Can operate with large datasets efficiently.

Simplicity:

 

  • Can be marginally complex for users implementing the ROW_NUMBER() and sub-queries.
  • It is best suited for users who want precise control of row ranking.

Conclusion

Since getting the second highest salary in SQL Server is a routine task, you will find the methods to do so in numbers. Then, we can learn and select the most practical method that fits our needs at that time. Each method has its good side, either in terms of simplicity, efficiency, or handling large datasets.

 

The mastery of these techniques aids not only in the SQL queries but also deepens our general understanding of the management of databases. On the whole, efficient querying leads to more performance and more meaning from the data analysis. By doing these types of practices, we can become proficient in SQL and can handle many kinds of data-related operations.

FAQs
The most efficient way to find the second highest salary is generally through either LIMIT and OFFSET or ROW_NUMBER() for huge data sets. These can work on a large amount of data very efficiently and provide results fast.
Yes, these methods can be adapted to find the Nth highest salary by adjusting the rank or limit parameters. For example, to find the third highest salary, you would set the rank to 3 in the ROW_NUMBER() method.
The nested query might make the subquery approach inefficient when dealing with very big datasets. It may also be less ideal in terms of performance than in other ways.
To make your queries effective, it is wise to index database columns, especially if the column is either in the ORDER BY or WHERE clause. It is recommended to analyse and update statistics frequently; it is also undesirable to use nested queries where they are not needed.
Yes, there are several ways to improve performance, for example, changing the SQL Server memory configuration, optimising disk I/O, and checking server resource utilisation. Also, with the help of query optimisation tools and techniques, performance can be made better.

Updated on July 29, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved