View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
SQL

SQL Tutorial: Learn Structured…

  • 81
  • 9 Hours

Find the Second Highest Salary in SQL

Updated on 31/01/2025473 Views

Introduction

Structured Query Language (SQL) is a founding premise for data manipulation and retrieval in database management. One of the key features of SQL is the ability to extract specific data from an intricate dataset, such as finding the second highest salary. In this piece, we will not only delve into the critical processes of retrieving the second highest salary in SQL, but will also explore the importance of mastering SQL queries and their real-life applications. A clear conceptual understanding of SQL is pivotal to database management and immensely helpful for professionals seeking expertise in data analysis.

The Fundamentals of SQL

Before we find the second highest salary in SQL, let's understand the basic concepts of SQL.

i) Decoding the SELECT statement

An overview:

The first step in retrieving specific information from a given dataset using SQL starts with the SELECT statement. Fundamentally, the SELECT statement functions as a query command that pinpoints the columns to be extracted from a data table or within multiple tables. Its flexible syntax allows users to generate customized queries to retrieve specific data.

Key elements:

  • The SELECT keyword: This is the initial signal to retrieve data from a given dataset.
  • Expressions or Column Names: In this step, the programmer defines the information to be retrieved. This typically consists of calculations, column names, or even aliases for columns.
  • The FROM clause: This clause is used to specify the tables from which the data is to be retrieved.

Example:

Let’s explain the concept with the following example:

SELECT employee_name, salary
FROM employees;

In this example, we can see how the SELECT statement operates:

  • SELECT initiates the query
  • ‘employee_name, salary’ identifies the specific column to be extracted
  • ‘FROM employees’ clarifies that information should be retrieved from the ‘employees’ table.

ii) Data Filtration with the WHERE Clause

An overview:

The WHERE clause is a conditional filter that empowers developers to retrieve only the necessary data from the table based on specific requirements. Because it can retrieve precise data as per specified conditions, the WHERE clause plays a critical role in SQL queries. By employing the WHERE clause, users can include rows that meet the conditions while excluding the ones that are not needed. The logical expressions are evaluated as either true or false.

Key components:

  • The WHERE keyword: This indicates that conditional filtering will be used in the SQL query.
  • Conditions: Logical expressions determine which rows will be included in the query result and are evaluated as true or false.

Example:

The following example will explain the concept further:

SELECT employee_name, salary
FROM employees
WHERE salary > 50000;

In this example:

  • ‘WHERE’ initiates conditional filtering.
  • ‘salary>50000’ specifies that only salaries above 50000 will be considered for this SQL query.

iii) Multiple Conditions in the WHERE clause

An overview:

Using the WHERE clause developers can use logical operators (‘AND’, ‘OR’, ‘NOT’) to combine multiple conditions. This feature makes data filtering more targeted and ensures that rows that meet all specified conditions or any one condition, as required by the user, are included in the final query result.

Key components:

  • Logical Operators (‘AND’, ‘OR’, ‘NOT’): These operators enable intricate filtering to extract precise data.
  • Parentheses: This sequences the order of evaluation when using multiple conditions.

Example:

The following example explains the concept:

SELECT employee_name, salary
FROM employees
WHERE department = 'IT' AND salary > 50000;

In this example:

‘WHERE department = 'IT' AND salary > 50000’ use the ‘AND’ operator to specify the rows where the retrieved department is ‘IT’ and salary is more than 50000.

iv) SELECT Multiple Columns

An overview:

SELECTing multiple columns provides the added advantage of specifying columns to meet case-specific requirements. Built upon the founding principles of the SELECT statement, this feature allows users to retrieve only specific data points from large databases.

Key components:

  • Column names: These fundamental elements are specified after the SELECT keyword to zero in on the target columns.
  • Table reference: Alternatively, a specific table can also be referred to for extracting data.

Example:

Let’s consider the following example:

SELECT employee_name, department, salary
FROM employees;

In this example:

  • ‘employee_name, department, salary’ identifies the columns for the SQL query
  • ‘FROM employees’ specifies that the data is to be extracted from the ‘employees’ table.

How to Find Second Highest Salary in SQL?

With the fundamental concepts of SQL in place, let us turn our attention to the core topic of this article: finding the second max salary in SQL

Before diving head-on into a SQL query to find the second highest salary, let’s understand its relevance in practical terms. In business scenarios, this information plays a vital role. It gives critical insights regarding salary discrepancies and pay-scale distribution, thus enabling the HR manager to make informed decisions about employee compensation.

  1. A Step-by-Step Process of Writing a SQL query

Let us assume we have a data table comprising of ‘employee_name’, and ‘salary’ columns. The following SQL query will help us with the 2nd highest salary in SQL:

SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

The query breakdown:

  • ‘SELECT Max(salary) FROM employees’ is the innermost query that extracts the highest salary from the given table.
  • The outer query, i.e., ‘WHERE salary < (SELECT MAX(salary) FROM employees)’ gives us the maximum salary after the highest amount, which is effectively the second highest salary in SQL.
  1. Some examples with keyword variations

Example 1: Using primary keyword

SELECT employee_name, salary
FROM employees;

In this example:

  • The SELECT statement extracts the data
  • ‘employee_name, salary’ are the source columns earmarked for the SQL query
  • FROM employees clearly states that the delivery is only to be taken from the ‘employees’ table.

This is a classic example of a focused query to select specified data within a dataset.

Example 2: Using secondary keyword

-- Using 2nd highest salary in SQL
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

In this example, we see that:

  • The SELECT statement retrieves the 2nd highest salary in SQL.
  • ‘MAX(salary) AS second_highest_salary’ extracts the second highest salary after the absolute max salary in SQL.
  • The WHERE clause filters out the highest salary and identifies the second highest salary.

Here, we see a more advanced query technique combining the SELECT statement with additional logic to extract the second max salary from the ‘employees’ table.

  1. Advanced SQL query

Though the above methods are effective enough to find the second highest salary in SQL, there are alternative options that may appeal to more advanced developers.

Using subqueries:

This power tool enables you to nest queries within a query. The following example uses a subquery to find the second highest salary in SQL.

SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary NOT IN (SELECT MAX(salary) FROM employees);

This example shows how to find the second highest salary by selecting the maximum salary that is not equal to the highest salary in SQL.

Deploying the Rank() Function

Using the Rank() function, you can assign a designated rank to each row based on the specified column value. We’ll now see how to find the 2nd highest salary in SQL.

SELECT salary
FROM (
SELECT salary, RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) AS ranked_employees
WHERE rnk = 2;

The rank function breaks the data into separate rows in descending order, or salaries. By selecting row 2, we get the second highest salary.

Using ‘Distinct’ and ‘Offset’

You can combine ‘ORDER BY’, ‘LIMIT’, and ‘DISTINCT’ clauses to get to the 2nd highest salary in SQL by using the ‘OFFSET’ clause. Let’s see how it’s done:

SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;

As we can see in this SQL query:

  • ‘ORDER BY salary DESC’ helps in arranging the salary in descending order
  • ‘LIMIT 1 OFFSET 1’ allows you to retrieve the second highest salary by omitting the highest salary.
  • ‘DISTINCT’ clause helps to extract the specified value even if multiple employees share the same salary.

Pros and Cons of Different Approaches

Both the traditional and advanced methods have their own benefits and pitfalls. Let’s consider some of them.

Traditional approach

Advantages:

  • Readability: Traditional methods using ‘Max()’ and ‘WHERE’ clauses are easy for developers and analysts to interpret and enhance readability.
  • Compatibility: These approaches' simplicity makes them compatible with most database systems that operate on basic SQL functions.

Disadvantages:

  • Lacks flexibility: For more complex datasets, these methods may not be effective in extracting the desired data.
  • Overall performance: These approaches may not work effectively when dealing with large databases. Using nested queries and combining statements can affect efficiency in certain cases.

Advanced methods

Advantages:

  • Precision performance: Subqueries or window functions like Rank() can extract accurate data within intricate datasets.
  • Enhanced efficiency: Advanced methods often produce better results when handling complex hierarchical data structures and particular query conditions than regular approaches.

Disadvantages:

  • Mature learning: Advanced methods mandate a more profound learning experience in SQL queries. Users or organizations adopting these methods should empower themselves with the right resources.
  • Lacks versatility: These approaches may not be compatible with all systems as they may have platform-specific features.

Real-world use cases of second highest salary in SQL

Finding the second highest salary goes beyond mere academic interest and has several practical uses.

  • Benchmarking salaries: Identifying the second maximum salary in the organization helps compare salary structures with industrial best practices.
  • Compensation analytics: HR departments are often tasked with deep analysis of employee compensations. The second highest salary is a critical yardstick for internal analysis and performance appraisals.
  • Detecting anomalies: Finding the second highest salary unearths discrepancies, if any, in the organizational salary structure.

Several industries need to find the second highest salary in SQL to optimize human resource productivity, reduce employee turnover, and remain competitive in the job market. BFSI, healthcare, and eCommerce are among the top users of this programming feature.

Conclusion

In this article, we explored the fundamentals of SQL querying, learned how to write queries using traditional and advanced techniques, and explored practical applications for finding the second highest salary in SQL. Keep nurturing your skills to master SQL queries that have widespread real-world uses.

FAQs

1) How do you SELECT 2 different values in SQL?

The SELECT statement allows you to extract two different values by extending the SELECT clause to include both columns. Let’s take a look at the following example:

SELECT column1, column2
FROM your_table;

As you can see in the above example:

  • The SQL query selects the data from the pre-defined columns, namely ‘column 1’ and ‘column 2’.
  • ‘FROM your_table’ specifies the main data source

This allows a more streamlined approach to data retrieval.

2) Can I use 2 WHERE in SQL?

While using two separate WHERE clauses is not allowed in a single SQL query, you can use two WHERE clauses, separated by logical operators, ‘AND’ or ‘OR.’

3) How do we use limits in SQL?

Using the LIMIT clause, you can restrict the number of rows the SQL query retrieves. For example:

SELECT *
FROM your_table
LIMIT 10;

In the above example, with the help of the LIMIT clause, the developer was able to restrict the rows to the top 10 records.

4) How do I filter two columns in SQL?

Filtering two columns in SQL involves using the WHERE clause with a logical operator to ensure conditions are met. The following example shows how it’s done:

SELECT employee_name, salary
FROM employees
WHERE salary > 50000
AND department = 'IT';

In this example:

  • The SQL query selects ‘employee_name, salary’ from the ‘employee’ table.
  • The WHERE clause, used in conjunction with the ‘AND’ logical operator, finds the required data of employees with salaries greater than 50000 in the IT department.

5) How do I find the last 5 records in SQL?

The first step is to use the ‘ORDER BY’ clause to sort the data in the selected column in descending order and then deploy the ‘LIMIT’ to find the last 5 records. We’ll show how it’s done below:

SELECT *
FROM your_table
ORDER BY timestamp_column DESC
LIMIT 5;

In the above example:

  • The SQL query selects all columns (*) from ‘your_table’.
  • Based on ‘tmestamp_column’ the results are sorted in descending order, and the ‘LIMIT 5’ clause gives you the desired data subset.
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.