To select 3rd highest salary in SQL, you can use the LIMIT clause in combination with the ORDER BY clause.
SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 2;
- We are assuming you have a table named
employeeswith a column namedsalarythat stores the salary information. - We use the
ORDER BYclause to sort the salaries in descending order (DESC), so the highest salary will come first. - We use
LIMIT 1to restrict the result set to just one row. - We use
OFFSET 2to skip the first two highest salaries, effectively selecting the 3rd highest salary.
Steps to Select 3rd Highest Salary in SQL
Now, Let’s see with the following steps –
1. Create the Database
You’ll need to have an SQL database system installed for example MySQL. Follow your database system’s documentation for installation and setup instructions.
2. Create the employees Table
This SQL command creates a table named employees with three columns: employee_id, employee_name, and salary. employee_id is the primary key, and salary is where you’ll store salary information
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(255),
salary DECIMAL(10, 2)
);
3. Insert Sample Data
Insert some sample data into the employees table
This command populates the employees table with sample employee data, including their names and salaries.
INSERT INTO employees (employee_id, employee_name, salary)
VALUES
(1, 'John', 50000.00),
(2, 'Alice', 60000.00),
(3, 'Bob', 55000.00),
(4, 'Eve', 75000.00),
(5, 'Mike', 62000.00);
4. Run the SQL Query
Run the SQL query mentioned earlier to find the 3rd highest salary
This query will return the 3rd highest salary from the employees table based on the sample data
SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 2;
Suggestion
This query will return the 3rd highest salary from the employees table. You can replace employees and salary with your actual table and column names as needed.
Remember to adapt the table structure and data to your specific use case as needed. The provided example is a simplified representation for demonstration purposes.