In almost every technical interview for software engineering, data engineering, application support, and DevOps roles, SQL questions are virtually guaranteed. While junior candidates can write basic `SELECT * FROM table WHERE id = 1`, technical interviewers look for mastery over joins, aggregations, correlated subqueries, and window functions.
Here are the top SQL interview questions with production-ready schemas, sample queries, and execution explanations.
---
Sample Schema Reference
Consider the following two tables used across the examples:
```sql
-- Employees Table
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(100),
dept_id INT,
salary DECIMAL(10, 2),
manager_id INT,
hire_date DATE
);
-- Departments Table
CREATE TABLE departments (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(100),
location VARCHAR(100)
);
```
---
1. Finding the Nth Highest Salary
Approach 1: Using DENSE_RANK() Window Function (Recommended)
```sql
WITH RankedSalaries AS (
SELECT
emp_id,
emp_name,
salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS rank_pos
FROM employees
)
SELECT emp_id, emp_name, salary
FROM RankedSalaries
WHERE rank_pos = 2; -- Change to N for Nth highest
```
Approach 2: Using Correlated Subquery (Universal ANSI SQL)
```sql
SELECT emp_name, salary
FROM employees e1
WHERE 2 = (
SELECT COUNT(DISTINCT e2.salary)
FROM employees e2
WHERE e2.salary >= e1.salary
);
```
---
2. Finding Duplicate Records in a Table
Query: Find duplicate email addresses
```sql
SELECT email, COUNT(*) AS duplicate_count
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
```
Follow-Up: How to delete duplicate records while keeping one?
```sql
WITH NumberedRecords AS (
SELECT
id,
email,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY id ASC) AS row_num
FROM users
)
DELETE FROM users
WHERE id IN (
SELECT id FROM NumberedRecords WHERE row_num > 1
);
```
---
3. Department-Wise Highest Salary
```sql
WITH RankedByDept AS (
SELECT
e.emp_name,
d.dept_name,
e.salary,
DENSE_RANK() OVER (PARTITION BY e.dept_id ORDER BY e.salary DESC) AS ranking
FROM employees e
JOIN departments d ON e.dept_id = d.dept_id
)
SELECT emp_name, dept_name, salary
FROM RankedByDept
WHERE ranking = 1;
```
---
4. Employees Earning More Than Their Managers (Self-Join)
```sql
SELECT
e.emp_name AS employee_name,
e.salary AS employee_salary,
m.emp_name AS manager_name,
m.salary AS manager_salary
FROM employees e
JOIN employees m ON e.manager_id = m.emp_id
WHERE e.salary > m.salary;
```
---
5. Finding Departments with No Employees
Approach 1: Using LEFT JOIN and IS NULL
```sql
SELECT d.dept_name
FROM departments d
LEFT JOIN employees e ON d.dept_id = e.dept_id
WHERE e.emp_id IS NULL;
```
Approach 2: Using NOT EXISTS (Optimized for Large Tables)
```sql
SELECT d.dept_name
FROM departments d
WHERE NOT EXISTS (
SELECT 1 FROM employees e WHERE e.dept_id = d.dept_id
);
```
---
6. Difference Between WHERE and HAVING
- `WHERE` Filter: Evaluates rows *before* any grouping or aggregation takes place. Cannot contain aggregate functions like
SUM()orCOUNT(). - `HAVING` Filter: Evaluates grouped records *after* the
GROUP BYoperation is executed.
```sql
SELECT dept_id, AVG(salary) AS avg_salary
FROM employees
WHERE hire_date >= '2024-01-01' -- Row level filter
GROUP BY dept_id
HAVING AVG(salary) > 75000; -- Group level filter
```
---
7. Running Cumulative Totals Using SUM() OVER()
```sql
SELECT
emp_id,
dept_id,
hire_date,
salary,
SUM(salary) OVER (
PARTITION BY dept_id
ORDER BY hire_date ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS cumulative_dept_spend
FROM employees;
```
---
8. Calculating Month-Over-Month Growth with LAG()
```sql
WITH MonthlyRevenue AS (
SELECT
DATE_TRUNC('month', order_date) AS order_month,
SUM(order_amount) AS current_month_revenue
FROM sales
GROUP BY DATE_TRUNC('month', order_date)
)
SELECT
order_month,
current_month_revenue,
LAG(current_month_revenue, 1) OVER (ORDER BY order_month) AS previous_month_revenue,
ROUND(
(current_month_revenue - LAG(current_month_revenue, 1) OVER (ORDER BY order_month))
/ LAG(current_month_revenue, 1) OVER (ORDER BY order_month) * 100, 2
) AS mom_growth_percentage
FROM MonthlyRevenue;
```
---
9. Finding Consecutive Active Days (Island and Gap Problem)
```sql
WITH RankedLogins AS (
SELECT
user_id,
login_date,
login_date - (DENSE_RANK() OVER (PARTITION BY user_id ORDER BY login_date)) * INTERVAL '1 day' AS grp
FROM user_logins
)
SELECT
user_id,
MIN(login_date) AS streak_start,
MAX(login_date) AS streak_end,
COUNT(*) AS consecutive_days
FROM RankedLogins
GROUP BY user_id, grp
HAVING COUNT(*) >= 5; -- Find users with 5+ day active streak
```
---
10. Pivoting Rows to Columns with CASE WHEN
```sql
SELECT
EXTRACT(YEAR FROM hire_date) AS hire_year,
COUNT(CASE WHEN dept_id = 101 THEN 1 END) AS engineering_count,
COUNT(CASE WHEN dept_id = 102 THEN 1 END) AS marketing_count,
COUNT(CASE WHEN dept_id = 103 THEN 1 END) AS sales_count,
COUNT(*) AS total_hires
FROM employees
GROUP BY EXTRACT(YEAR FROM hire_date)
ORDER BY hire_year DESC;
```
---
11. Finding Missing IDs in a Sequential Number Range
```sql
SELECT current_id + 1 AS missing_id_start
FROM (
SELECT id AS current_id, LEAD(id) OVER (ORDER BY id) AS next_id
FROM invoice_sequences
) seq
WHERE next_id - current_id > 1;
```
---
12. Query Optimization Tips for Technical Interviews
- Check Index Scans via `EXPLAIN ANALYZE`: Understand the difference between an
Index Scan(fetches data pages via B-Tree pointers),Index Only Scan(answers entire query from index keys without touching table heap), andSeq Scan(full table scan). - Avoid Wildcard Matching at the Start of Strings: Queries like
WHERE name LIKE '%john'cannot utilize standard B-Tree indexes and trigger slow full table scans. PreferLIKE 'john%'or use trigram GIN indexes. - Use `EXISTS` Instead of `IN` for Large Subqueries:
EXISTSterminates evaluation on the first matching record (short-circuiting), whereasINtypically builds the entire distinct subquery result set in memory. - Never Use `SELECT *` in Production Queries: Always project explicitly required columns to minimize I/O, reduce cache eviction, and optimize network serialization.

Abu
Founder of GetJobWithAbuCloud & Azure Developer (5+ Years IT Exp)Cloud & Azure Developer with 5+ years of IT industry experience, having transitioned from a 4.8-year IT Support role into Software & Cloud Development. Dedicated to helping freshers, Tier-2/Tier-3 college graduates, and IT support engineers crack technical interviews through practical production insights, real-world scenario questions, and hands-on guidance.
Related Technical Guides & Interview Prep
Linux Interview Q&A (30 Scenarios)
Process inspection, memory pressure, strace, and kernel triage fundamentals.
DevOps & CI/CD Scenario Prep
Docker optimization, Kubernetes troubleshooting, and automated quality gates.
SQL Query Scenarios for IT Interviews
Indexing strategies, window functions, and query optimization for high load.
Grafana & Observability Scenarios
PromQL, LogQL, Loki, and real-time production incident alerting.
Python Troubleshooting & OOP
Concurrency, memory management, decorators, and REST API design patterns.
Crack Company Blueprints
Round-by-round hiring breakdowns for TCS, Infosys, Zoho, Accenture, and Wipro.
Share This Opportunity
Related Articles
Top 5 Mistakes Freshers Make in Technical Interviews (And How to Fix Them)
Based on coaching 100+ candidates, here are the most common mistakes freshers make in technical interviews and actionable solutions for each.
How to Crack TCS Interview: Complete Guide 2026
Master TCS interview in 30 days with proven strategies, technical questions, and insider tips from successful candidates.
How to Crack Infosys Interview 2026: Complete Round-by-Round Guide
Master every round of the Infosys interview process โ from InfyTQ to technical rounds and HR. Real strategies from coaching 50+ Infosys aspirants.