Last updated: October 2026
SQL is the one skill that shows up in almost every tech interview in India. Data analysts get tested on it, obviously. But so do backend developers, QA engineers, business analysts and even product managers at data-heavy companies. If a job description mentions "data", expect at least one SQL question.
The good news: the question pool is smaller than it looks. Interviewers keep coming back to the same 15 or 20 ideas, joins, grouping, NULLs, ranking, and dress them up in different tables. This guide covers 60 questions in the order most interviews move: basics first, then the query round, then the "how would you design or speed this up" round for experienced folks.
Already comfortable with the basics? Jump to our advanced SQL interview questions for recursive CTEs, PIVOT, MERGE and temporal tables.
SQL interview questions: the quick answer
- What gets tested: joins, GROUP BY with HAVING, subqueries, NULL handling, window functions (RANK, ROW_NUMBER, LAG), indexes and basic normalization.
- Typical format: 1 online test (MCQs + 2–3 queries on HackerRank or similar), then 1 live round where you write queries on a shared screen and explain them.
- The 5 queries you must be able to write cold: second-highest salary, duplicates, employees earning more than their manager, top N per group, running total.
- Fresher vs experienced: freshers are judged on correct syntax and clear thinking. Experienced candidates are judged on performance, execution plans and data modelling choices.
How SQL interviews actually run
Most companies follow a similar pattern. Service companies like TCS and Infosys ask theory questions (DDL vs DML, keys, normalization) mixed with one or two simple queries. Product companies and analytics teams skip most theory and hand you two or three tables, usually employees, departments and orders, and ask you to answer business questions with them.
One habit that helps in both: say your assumptions out loud. "I'm assuming one employee can only belong to one department" takes three seconds and saves you from writing the wrong join.
We use a standard set of tables in the examples below:
employees(id, name, salary, dept_id, manager_id, joined_on)
departments(id, name)
orders(id, customer_id, amount, order_date)
customers(id, name, city)
Fresher-level SQL interview questions (1–20)
1. What is SQL?
SQL (Structured Query Language) is the standard language for storing, reading and changing data in relational databases like MySQL, PostgreSQL, SQL Server and Oracle. You describe what data you want, and the database works out how to fetch it.
2. What is the difference between SQL and MySQL?
SQL is the language. MySQL is one database product that understands that language. PostgreSQL, Oracle and SQL Server are others. Each adds a few features of its own, for example LIMIT in MySQL and PostgreSQL versus TOP in SQL Server.
3. What are DDL, DML, DCL and TCL?
| Type | Stands for | Commands |
|---|---|---|
| DDL | Data Definition Language | CREATE, ALTER, DROP, TRUNCATE |
| DML | Data Manipulation Language | SELECT, INSERT, UPDATE, DELETE |
| DCL | Data Control Language | GRANT, REVOKE |
| TCL | Transaction Control Language | COMMIT, ROLLBACK, SAVEPOINT |
Some textbooks put SELECT in its own group called DQL. Either answer is accepted.
4. What is a primary key?
A column (or set of columns) that uniquely identifies each row. It cannot be NULL and cannot repeat. A table can have only one primary key, though that key can span more than one column.
5. What is a foreign key?
A column that points to the primary key of another table. It keeps data consistent: you can't add an employee with dept_id = 9 if department 9 doesn't exist.
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(id)
);
6. What is the difference between a primary key and a unique key?
Both prevent duplicates. A primary key can't be NULL and there's only one per table. A unique key allows NULLs (one NULL in SQL Server, many in MySQL and PostgreSQL) and you can have several unique keys on one table.
7. What are constraints in SQL?
Rules on columns that stop bad data getting in: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK (for example CHECK (salary > 0)) and DEFAULT.
8. What is the difference between DELETE, TRUNCATE and DROP?
| DELETE | TRUNCATE | DROP | |
|---|---|---|---|
| Removes | Selected rows (with WHERE) | All rows | The whole table |
| Can use WHERE | Yes | No | No |
| Rollback | Yes, inside a transaction | Depends on the database | Depends on the database |
| Speed | Slowest (row by row) | Fast | Fast |
| Table structure | Stays | Stays | Gone |
9. What is the difference between WHERE and HAVING?
WHERE filters rows before grouping. HAVING filters groups after aggregation. You can't use COUNT() or SUM() in WHERE.
SELECT dept_id, COUNT(*) AS headcount
FROM employees
WHERE salary > 30000 -- row filter
GROUP BY dept_id
HAVING COUNT(*) > 5; -- group filter
10. What is the order of execution of a SQL query?
FROM and JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. This is why you can't use a column alias from SELECT inside WHERE: WHERE runs first. Most databases do let you use it in ORDER BY.
11. What are the different types of joins?
- INNER JOIN: only rows that match in both tables.
- LEFT JOIN: all rows from the left table, matched rows from the right, NULL where there's no match.
- RIGHT JOIN: the mirror of LEFT JOIN.
- FULL OUTER JOIN: all rows from both sides. MySQL doesn't support it directly; you combine LEFT and RIGHT joins with UNION.
- CROSS JOIN: every row paired with every row.
- SELF JOIN: a table joined with itself, usually for manager–employee data.
12. What is the difference between UNION and UNION ALL?
UNION removes duplicate rows, which means an extra sort or hash step. UNION ALL keeps everything and is faster. Use UNION ALL unless you actually need duplicates removed.
13. What does NULL mean, and how do you check for it?
NULL means "unknown" or "missing". It isn't zero or an empty string. Any comparison with NULL using = returns unknown, so you must use IS NULL or IS NOT NULL.
SELECT name FROM employees WHERE manager_id IS NULL; -- the CEO
14. What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?
COUNT(*) counts all rows. COUNT(column) skips rows where that column is NULL. COUNT(DISTINCT column) counts unique non-NULL values. This tiny difference trips up a lot of people in MCQ rounds.
15. What are aggregate functions?
Functions that turn many rows into one value: COUNT, SUM, AVG, MIN, MAX. All of them except COUNT(*) ignore NULLs.
16. What does GROUP BY do?
It collapses rows that share a value into one row per group, so you can run aggregates on each group. Every non-aggregated column in SELECT must be in the GROUP BY.
SELECT d.name, AVG(e.salary) AS avg_salary
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.name;
17. What is the difference between CHAR and VARCHAR?
CHAR(10) always uses 10 characters of storage and pads shorter values with spaces. VARCHAR(10) uses only what the value needs. Use CHAR for fixed-length codes like country codes, and VARCHAR for names and emails.
18. What is the LIKE operator?
Pattern matching on text. % matches any number of characters and _ matches exactly one.
SELECT name FROM customers WHERE name LIKE 'A%'; -- starts with A
SELECT name FROM customers WHERE name LIKE '_a%'; -- second letter is a
19. What is the difference between IN and BETWEEN?
IN checks against a list: city IN ('Pune', 'Delhi'). BETWEEN checks a range and includes both ends: salary BETWEEN 30000 AND 50000.
20. What is a view?
A saved SELECT query that you can treat like a table. It doesn't store data itself (unless it's a materialized view). Teams use views to hide complex joins and to limit which columns certain users can see.
CREATE VIEW high_earners AS
SELECT name, salary FROM employees WHERE salary > 100000;
Intermediate SQL query questions (21–42)
This is the round where you write queries live. Speak while you type. Interviewers care about your approach as much as the final query.
21. Find the second-highest salary.
The single most asked SQL question in India. Know at least two ways.
-- Way 1: subquery
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
-- Way 2: DENSE_RANK (handles ties and works for any N)
SELECT DISTINCT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) t
WHERE rnk = 2;
Mention that Way 2 is easier to change into "third highest" or "Nth highest".
22. Find the Nth highest salary using LIMIT and OFFSET.
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2; -- 3rd highest (OFFSET = N - 1)
23. Find duplicate records in a table.
SELECT email, COUNT(*) AS times
FROM customers
GROUP BY email
HAVING COUNT(*) > 1;
24. Delete duplicates but keep one copy.
DELETE FROM customers
WHERE id NOT IN (
SELECT keep_id FROM (
SELECT MIN(id) AS keep_id FROM customers GROUP BY email
) t
);
The extra wrapper SELECT ... ) t is needed in MySQL, which doesn't let you select from the same table you're deleting from directly.
25. Find employees who earn more than their manager.
SELECT e.name AS employee, m.name AS manager
FROM employees e
JOIN employees m ON e.manager_id = m.id
WHERE e.salary > m.salary;
A classic self join. Name your aliases clearly, e and m, so the interviewer can follow.
26. Find the highest-paid employee in each department.
SELECT dept_id, name, salary
FROM (
SELECT dept_id, name, salary,
RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk
FROM employees
) t
WHERE rnk = 1;
RANK keeps ties. If two people share the top salary, both come back. Say that out loud; it shows you thought about edge cases.
27. What is the difference between RANK, DENSE_RANK and ROW_NUMBER?
For salaries 90, 80, 80, 70:
| Salary | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 90 | 1 | 1 | 1 |
| 80 | 2 | 2 | 2 |
| 80 | 3 | 2 | 2 |
| 70 | 4 | 4 | 3 |
28. Find departments with no employees.
SELECT d.name
FROM departments d
LEFT JOIN employees e ON e.dept_id = d.id
WHERE e.id IS NULL;
This "LEFT JOIN + IS NULL" pattern is called an anti-join. You can also write it with NOT EXISTS.
29. Find customers who never placed an order.
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.id
);
Prefer NOT EXISTS over NOT IN here. If the subquery returns even one NULL, NOT IN returns no rows at all, a famous bug.
30. Calculate a running total of sales by date.
SELECT order_date,
amount,
SUM(amount) OVER (ORDER BY order_date) AS running_total
FROM orders;
31. Get the top 3 orders for each customer.
SELECT * FROM (
SELECT o.*,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn
FROM orders o
) t
WHERE rn <= 3;
32. Find month-on-month sales growth.
WITH monthly AS (
SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(amount) AS sales
FROM orders
GROUP BY month
)
SELECT month, sales,
LAG(sales) OVER (ORDER BY month) AS prev_month,
ROUND(100 * (sales - LAG(sales) OVER (ORDER BY month))
/ LAG(sales) OVER (ORDER BY month), 1) AS growth_pct
FROM monthly;
In PostgreSQL, use TO_CHAR(order_date, 'YYYY-MM') instead of DATE_FORMAT.
33. What is a subquery, and what is a correlated subquery?
A subquery is a query inside another query. A normal subquery runs once. A correlated subquery refers to the outer query, so it logically runs once per outer row:
-- employees earning above their own department's average
SELECT name, salary
FROM employees e
WHERE salary > (
SELECT AVG(salary) FROM employees WHERE dept_id = e.dept_id
);
34. What is a CTE?
A Common Table Expression is a named temporary result you define with WITH and use in the next query. It makes long queries readable, and a recursive CTE can walk hierarchies like org charts.
35. What is the CASE statement?
SQL's if-else. Very common in analyst interviews for bucketing data.
SELECT name,
CASE
WHEN salary >= 100000 THEN 'High'
WHEN salary >= 50000 THEN 'Mid'
ELSE 'Entry'
END AS band
FROM employees;
36. How do you count employees per salary band in one query?
SELECT
SUM(CASE WHEN salary < 50000 THEN 1 ELSE 0 END) AS entry,
SUM(CASE WHEN salary BETWEEN 50000 AND 99999 THEN 1 ELSE 0 END) AS mid,
SUM(CASE WHEN salary >= 100000 THEN 1 ELSE 0 END) AS high
FROM employees;
This "conditional aggregation" trick replaces three separate queries.
37. Find employees who joined in the last 90 days.
-- MySQL
SELECT name FROM employees WHERE joined_on >= CURDATE() - INTERVAL 90 DAY;
-- PostgreSQL
SELECT name FROM employees WHERE joined_on >= CURRENT_DATE - INTERVAL '90 days';
38. What is COALESCE?
It returns the first non-NULL value in a list. Handy for showing defaults: COALESCE(phone, 'Not given').
39. Fetch alternate (odd-numbered) rows from a table.
SELECT * FROM (
SELECT e.*, ROW_NUMBER() OVER (ORDER BY id) AS rn FROM employees e
) t
WHERE rn % 2 = 1;
40. Find the employee count and the average salary per department, but only for departments averaging above ₹60,000.
SELECT d.name, COUNT(*) AS headcount, ROUND(AVG(e.salary)) AS avg_salary
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.name
HAVING AVG(e.salary) > 60000
ORDER BY avg_salary DESC;
41. Find customers who ordered in every month of 2026 so far.
SELECT customer_id
FROM orders
WHERE order_date >= '2026-01-01'
GROUP BY customer_id
HAVING COUNT(DISTINCT MONTH(order_date)) = MONTH(CURDATE());
Interviewers like this one because it tests whether you think of COUNT(DISTINCT ...).
42. Swap the values of a gender column ('M' to 'F' and 'F' to 'M') in one UPDATE.
UPDATE employees
SET gender = CASE WHEN gender = 'M' THEN 'F' ELSE 'M' END;
Experienced-level SQL interview questions (43–60)
With 3+ years of experience, the questions move from "can you write it" to "can you make it fast, safe and maintainable".
43. What is an index, and how does it speed up queries?
An index is a separate sorted structure, usually a B-tree, that lets the database find rows without scanning the whole table. Think of the index at the back of a book. The trade-off: every INSERT, UPDATE and DELETE also has to update the index, and indexes take disk space.
44. What is the difference between a clustered and a non-clustered index?
A clustered index decides the physical order of rows on disk, so a table has only one (in MySQL InnoDB, it's the primary key). A non-clustered index is a separate structure that stores the indexed value plus a pointer to the row. You can have many.
45. What is a composite index, and does column order matter?
An index on more than one column, for example (dept_id, salary). Order matters a lot. This index helps queries filtering on dept_id alone or on dept_id AND salary, but not queries filtering only on salary. That's the "leftmost prefix" rule.
46. When will a query not use an index even though one exists?
Common reasons:
- A function on the indexed column:
WHERE YEAR(joined_on) = 2026(rewrite as a date range). - A leading wildcard:
LIKE '%kumar'. - Implicit type conversion, such as comparing a VARCHAR column to a number.
- Low selectivity: if the filter matches most of the table, a full scan is cheaper.
ORacross different columns, in some databases.
47. How do you find out why a query is slow?
Run EXPLAIN (or EXPLAIN ANALYZE in PostgreSQL and MySQL 8) and read the plan. Look for full table scans on big tables, wrong join order, huge row estimates and filesorts. Then fix the cause: add or adjust an index, rewrite the query, or reduce the rows earlier.
48. What is normalization? Explain 1NF, 2NF and 3NF.
Normalization means organising tables so that each fact is stored once.
- 1NF: each column holds one value, with no lists inside a cell.
- 2NF: 1NF, and every non-key column depends on the whole primary key, not part of it.
- 3NF: 2NF, and non-key columns don't depend on other non-key columns. For example, don't store
dept_namein employees whendept_idalready points to it.
Our DBMS interview questions go deeper into BCNF and functional dependencies.
49. When would you denormalize?
For read-heavy reporting where joins become the bottleneck: dashboards, analytics tables, search indexes. You accept some duplicated data in exchange for faster reads, and you need a plan for keeping the copies in sync.
50. What are ACID properties?
- Atomicity: a transaction fully happens or doesn't happen at all.
- Consistency: it moves the database from one valid state to another.
- Isolation: concurrent transactions don't see each other's half-done work.
- Durability: once committed, it survives crashes.
The textbook example is a bank transfer: debit and credit must both succeed or both roll back.
51. What are transaction isolation levels?
From weakest to strongest: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ and SERIALIZABLE. Higher levels block more anomalies (dirty reads, non-repeatable reads, phantom reads) but reduce concurrency. MySQL InnoDB defaults to REPEATABLE READ; PostgreSQL and SQL Server default to READ COMMITTED.
52. What is a deadlock, and how do you prevent one?
Two transactions each hold a lock the other needs, so both wait forever. The database detects this and kills one. To prevent deadlocks: access tables and rows in the same order everywhere, keep transactions short, and index the columns you filter on so fewer rows get locked.
53. What is the difference between a view and a materialized view?
A view runs its query every time you read it. A materialized view stores the result and must be refreshed. Use a materialized view for expensive reports that can be a few minutes or hours old.
54. What is a stored procedure, and how is it different from a function?
Both are saved blocks of SQL logic. A function returns a value and can be used inside a SELECT. A stored procedure can return zero or many result sets, can manage transactions, and is called with CALL or EXEC. Functions generally shouldn't change data.
55. What is a trigger?
Code that runs automatically when an INSERT, UPDATE or DELETE happens on a table, for example writing an audit row every time a salary changes. Use triggers sparingly; hidden logic makes debugging painful.
56. How would you paginate a large result efficiently?
LIMIT 20 OFFSET 100000 gets slow because the database still reads and throws away 100,000 rows. Keyset (cursor) pagination is faster:
SELECT id, name FROM employees
WHERE id > 100020 -- last id from the previous page
ORDER BY id
LIMIT 20;
57. What is SQL injection, and how do you prevent it?
An attack where user input is glued into a query string and changes what the query does, for example a login field containing ' OR '1'='1. Prevent it with parameterized queries or prepared statements, never by building SQL with string concatenation. Least-privilege database users limit the damage if something slips through.
58. What is the difference between OLTP and OLAP?
OLTP (online transaction processing) handles many small, fast reads and writes, such as orders and payments. OLAP (online analytical processing) handles fewer, heavy queries over lots of historical data, such as monthly revenue by region. OLTP schemas are normalized; OLAP usually uses star or snowflake schemas in a warehouse like BigQuery, Snowflake or Redshift.
59. What is partitioning?
Splitting one large table into smaller pieces, usually by date or by a key range, while still querying it as one table. Queries that filter on the partition key only touch the relevant pieces ("partition pruning"), and old data can be archived by dropping a partition.
60. A dashboard query that took 2 seconds now takes 40. How do you debug it?
A strong answer is a process, not a guess:
- Check what changed: data volume, a new deployment, a dropped index, stale statistics.
- Run
EXPLAIN ANALYZEand compare with the old plan if you have it. - Look for a scan where there used to be an index seek, or a bad row estimate.
- Fix the cause: refresh statistics, restore or add an index, rewrite the query, or pre-aggregate into a summary table.
- Add monitoring so the next slowdown is caught early.
Common mistakes candidates make
- Writing
= NULLinstead ofIS NULL. - Using
NOT INwith a subquery that can return NULLs. - Forgetting ties in "highest salary" questions. Ask whether ties should be included.
- Putting aggregate conditions in WHERE instead of HAVING.
- Jumping straight into typing. Spend 30 seconds restating the question and the tables you'll need.
- Using
SELECT *in a performance discussion. It signals you haven't thought about what you need.
A 7-day SQL prep plan
| Day | Focus | Practice |
|---|---|---|
| 1 | SELECT, WHERE, ORDER BY, LIMIT, NULLs | 15 easy problems |
| 2 | Joins: inner, left, self, anti-join | 10 join problems |
| 3 | GROUP BY, HAVING, CASE, conditional aggregation | 10 problems |
| 4 | Subqueries, EXISTS, CTEs | 8 problems |
| 5 | Window functions: RANK, ROW_NUMBER, LAG, running totals | 10 problems |
| 6 | Indexes, EXPLAIN, normalization, transactions | Read and explain out loud |
| 7 | Two timed mock tests of 45 minutes each | Review every mistake |
LeetCode's SQL 50 list, HackerRank's SQL track and DB Fiddle for quick experiments are enough. You don't need a paid course.
Which roles ask SQL, and what they pay
SQL is a must-have for data analysts, data engineers, BI developers, backend developers and QA engineers who test data pipelines. If you're aiming for analytics roles, see our data analyst salary guide and the business analyst salary guide for 2026 pay by experience and city. Company-wise numbers are on Weekday's salary pages.
Related reading: Power BI interview questions, MongoDB interview questions and SQL developer resume examples.
Frequently asked questions
What are the most asked SQL interview questions for freshers?
Second-highest salary, the difference between WHERE and HAVING, DELETE vs TRUNCATE vs DROP, types of joins, primary vs foreign key, and finding duplicates. Get these six right and you'll clear most fresher rounds.
Is SQL enough to get a job?
On its own, rarely. Paired with Excel and a BI tool like Power BI or Tableau, it's enough for many entry-level data analyst roles. Paired with Python, it opens up data engineering and analytics engineering.
Which SQL database should I practise on?
MySQL or PostgreSQL. Both are free and widely used in Indian companies. The core syntax is about 90% the same, so skills carry over to SQL Server and Oracle.
How long does it take to prepare for a SQL interview?
If you know the basics, 1–2 weeks of daily practice is enough for fresher and analyst roles. For senior roles, add time for indexing, execution plans and data modelling.
Do interviews ask window functions?
Yes, increasingly, even for freshers at product companies and analytics teams. At minimum know ROW_NUMBER, RANK, DENSE_RANK, LAG and SUM() OVER.
Done prepping? Put it to use. Find SQL and data jobs on Weekday, and run your resume through our free ATS resume checker before you apply.




