reviewer

Reviewer

View the Project on GitHub

Navigation: Index Azure .NET SQL React General

SQL

SQL get second highest salary

To get the second highest salary from an employee record in SQL, you can use various approaches depending on the SQL database you are using. Here are some common methods that work for different SQL databases. Which one works best depends on your database system and whether salaries have duplicates.

1. Using LIMIT and OFFSET (MySQL, PostgreSQL)

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

2. Using MAX() and NOT IN (Works in most SQL databases)

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

3. Using DENSE_RANK() (Best for handling duplicate salaries)

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

4. Using TOP (SQL Server)

SELECT TOP 1 salary 
FROM (
    SELECT DISTINCT TOP 2 salary 
    FROM employees 
    ORDER BY salary DESC
) AS temp 
ORDER BY salary ASC;

What are JOINs in SQL?

In SQL, JOINs are used to combine rows from two or more tables based on a related column. This allows querying data that is stored across multiple tables.

Types of SQL JOINs

1. INNER JOIN (Most Common)

2. LEFT JOIN (or LEFT OUTER JOIN)

3. RIGHT JOIN (or RIGHT OUTER JOIN)

4. FULL JOIN (or FULL OUTER JOIN)

5. CROSS JOIN

6. SELF JOIN

Summary Table

JOIN Type Matching Rows? Non-Matching Rows?
INNER JOIN ✅ Yes (Both Tables) ❌ No
LEFT JOIN ✅ Yes (Both Tables) ✅ Yes (Left Table)
RIGHT JOIN ✅ Yes (Both Tables) ✅ Yes (Right Table)
FULL JOIN ✅ Yes (Both Tables) ✅ Yes (Both Tables)
CROSS JOIN ❌ No Condition ✅ All Combinations
SELF JOIN ✅ Yes (Same Table) ❌ No

Use Case Examples:

How do you optimize SQL queries for performance?

Optimizing SQL queries is crucial for improving database performance, reducing execution time, and minimizing resource consumption. Here are some key techniques:

1. Use Proper Indexing

What is Indexing in SQL?

Indexing in SQL is a technique used to improve the speed of data retrieval from a database table. An index is similar to a book’s table of contents—it allows the database to quickly locate and fetch the requested data instead of scanning the entire table.

Types of Indexes in SQL

1. Primary Index (Clustered Index)

2. Unique Index

3. Non-Clustered Index

4. Composite Index (Multi-Column Index)

5. Full-Text Index

Advantages of Indexing

Disadvantages of Indexing

When to Use Indexing?


← .NET | Back to Index | React →