🎬No video for this question yet. The written answer is below.
Find the second highest salary from a table.- Difference between ROW_NUMBER(), RANK(), and DENSE_RANK().
- How do you remove duplicate records from a table?
- Explain different types of joins with use cases.
- How do you optimize a slow-running SQL query?
📝 Answer
SQL Interview Answers
Simple English · Clear explanation · 3-minute speaking format
1
Find Second Highest Salary
Approach 1 — Subquery
- Find the maximum salary first
- Then find the maximum salary that is less than that
- Works well when salaries are unique
1SELECT MAX(salary)2FROM employees3WHERE salary < (SELECT MAX(salary) FROM employees);
Approach 2 — DENSE_RANK (Preferred)
- More flexible and handles duplicate salaries properly
- Easily extendable to Top N results
- Preferred in real-world large datasets
1SELECT salary2FROM (3 SELECT salary,4 DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk5 FROM employees6) t7WHERE rnk = 2;
Change rnk = 2 to rnk = N for any Top-N salary
How to Say It in Interview
🎤 Speak This
There are multiple ways to find the second highest salary. The most common way is using a subquery — first find the maximum salary, then find the maximum salary which is less than that.But a better approach is using DENSE_RANK. This handles duplicates properly. For example, if multiple employees have the same highest salary, DENSE_RANK will still correctly give the second highest.
In real projects, I prefer window functions because they are more readable and scalable, especially when we need top N results.
2
ROW_NUMBER vs RANK vs DENSE_RANK
How They Differ
| Function | Duplicates? | Skips Numbers? | Use When |
|---|---|---|---|
| ROW_NUMBER() | Unique number always | No skip | Removing duplicates, pagination |
| RANK() | Same rank for ties | Yes — gaps after ties | Rankings where gaps are OK |
| DENSE_RANK() | Same rank for ties | No — continuous | Top N salaries, leaderboards |
Example — Salaries: 100, 100, 90
Result for each function
100
ROW_NUMBER →
1
· RANK → 1 · DENSE_RANK → 1
100
ROW_NUMBER →
2
· RANK → 1 · DENSE_RANK → 1
90
ROW_NUMBER →
3
· RANK → 3 (skips 2) · DENSE_RANK → 2
How to Say It in Interview
🎤 Speak This
These are window functions used for ranking data, but the difference is how they handle duplicates.ROW_NUMBER gives a unique number to each row. Even if values are the same, it assigns different numbers.
RANK gives the same rank for duplicates, but it skips numbers after that.
DENSE_RANK also gives the same rank for duplicates, but it does not skip numbers.
In real projects — I use ROW_NUMBER when I want unique records, like removing duplicates. I use DENSE_RANK when I need continuous ranking, like top 2 or top 3 salaries. So choosing the function depends on the business requirement.
🔥 Real Use Cases
ROW_NUMBER → Deduplication in ETL pipelines (keep one record per group)
RANK → Sports leaderboards where ties share a rank
DENSE_RANK → "Find employees with top 3 salaries" type queries
RANK → Sports leaderboards where ties share a rank
DENSE_RANK → "Find employees with top 3 salaries" type queries
3
Remove Duplicate Records
Approach 1 — ROW_NUMBER (Full Control)
- Partition by duplicate columns, keep only the first record
- Can choose which record to keep — by ID, timestamp, etc.
- Best for ETL pipelines where data comes from multiple sources
1DELETE FROM employees2WHERE id IN (3 SELECT id FROM (4 SELECT id,5 ROW_NUMBER() OVER (6 PARTITION BY name, salary7 ORDER BY id8 ) AS rn9 FROM employees10 ) t11 WHERE rn > 112);
Approach 2 — DISTINCT (Read Only)
- Shows unique records in result — does not delete data
- Simple and fast for reporting queries
1SELECT DISTINCT * FROM employees;
How to Say It in Interview
🎤 Speak This
Removing duplicates depends on whether we want to keep one record or remove all duplicates.The most common method is using ROW_NUMBER. We partition by duplicate columns and keep only the first record. I prefer this because it gives full control — I can decide which record to keep based on timestamp or ID.
Another simple way is using DISTINCT — but this only shows unique data in the result, it does not delete from the table.
This is very common in ETL pipelines where duplicate data comes from multiple sources.
📌 ETL Pipeline Tip
In AWS Glue or Redshift pipelines, always deduplicate using ROW_NUMBER after loading raw data into staging. Partition by business key columns and order by created_at DESC to keep the latest record.
4
Types of Joins with Use Cases
Quick Reference
| Join Type | What It Returns | No Match → ? | Real Use Case |
|---|---|---|---|
| INNER JOIN | Matching rows from both tables | Row excluded | Orders + Customers (matched only) |
| LEFT JOIN | All rows from left + matches from right | NULL on right side | All customers, even without orders |
| RIGHT JOIN | All rows from right + matches from left | NULL on left side | All products, even unsold ones |
| FULL JOIN | All rows from both tables | NULL on either side | Data comparison / reconciliation |
| CROSS JOIN | All combinations (cartesian) | N/A | Generate combinations (rare) |
How to Say It in Interview
🎤 Speak This
Joins are used to combine data from multiple tables based on a condition.INNER JOIN returns only matching records from both tables. For example, joining orders and customers where customer_id matches.
LEFT JOIN returns all records from the left table and matching records from the right. If no match, it returns NULL. This is very common in reporting and data pipelines.
FULL JOIN returns all records from both tables, matching where possible. This is used in data comparison or reconciliation scenarios.
So the choice of join depends on business requirement and data completeness.
5
Optimizing a Slow SQL Query
Structured Optimization Steps
| Step | What to Do | Why It Helps |
|---|---|---|
| 1 | Check execution plan (EXPLAIN / EXPLAIN ANALYZE) | Find full table scans and bottlenecks |
| 2 | Add proper indexes on filter and join columns | Faster data retrieval |
| 3 | Avoid SELECT * — select only required columns | Reduces data scanned and transferred |
| 4 | Simplify or reduce joins | Complex joins multiply row processing cost |
| 5 | Use partitioning (Redshift / BigQuery / S3) | Reads only relevant partition → huge speed gain |
| 6 | Replace subqueries with CTEs or joins | Often more readable and better optimized |
How to Say It in Interview
🎤 Speak This
When a SQL query is slow, I follow a structured approach to optimize it.First, I check the execution plan to understand where time is spent. This helps identify bottlenecks like full table scan or expensive joins.
Second, I make sure proper indexes are used on filter and join columns.
Third, I avoid selecting unnecessary columns. Instead of SELECT *, I select only required columns.
Fourth, I check for data size and partitioning. In systems like Redshift or BigQuery, proper distribution and partitioning improve performance significantly.
Also, I replace expensive subqueries with joins or CTEs when needed.
Overall, optimization is about reducing data scan, minimizing computation, and using indexes effectively.
🔥 AWS Redshift Specific
In Redshift, always define proper DISTKEY (distribution key) and SORTKEY on tables. Queries on SORTKEY columns skip unnecessary blocks — this is called zone map pruning and dramatically reduces I/O.
🎯 How to Speak in the Interview
- Speak slowly — don't rush into SQL code
- Give a small real example before the query
- Explain why, not just how
- Mention real tools: Redshift, BigQuery, Athena