Interview questions › SQL
SQL interview questions
1. What is SQL?
Easy
Structured Query Language — the standard language to create, read, update and delete data in relational databases (MySQL, PostgreSQL, SQL Server, Oracle, SQLite).
2. What are DDL, DML, DCL and TCL?
Easy
DDL defines structure: CREATE, ALTER, DROP, TRUNCATE. DML works with data: SELECT, INSERT, UPDATE, DELETE. DCL controls access: GRANT, REVOKE. TCL controls transactions: COMMIT, ROLLBACK, SAVEPOINT.
3. Primary key vs unique key?
Easy
A primary key uniquely identifies each row, cannot be NULL, and there is only one per table. A unique key also forbids duplicates but allows a NULL (one in most databases), and a table can have several.
4. What is a foreign key?
Easy
A column that references the primary key of another table, enforcing referential integrity — you cannot insert an order for a customer that doesn't exist. ON DELETE CASCADE deletes the child rows too.
5. DELETE vs TRUNCATE vs DROP?
Easy
DELETE removes chosen rows (with WHERE), is logged row by row and can be rolled back. TRUNCATE removes all rows quickly and resets identity counters. DROP deletes the whole table and its structure.
6. WHERE vs HAVING?
Easy
WHERE filters rows before grouping and cannot use aggregates. HAVING filters groups after GROUP BY and can use aggregates.
SELECT dept, COUNT(*) FROM emp
WHERE active = 1
GROUP BY dept
HAVING COUNT(*) > 5;
7. What is the logical order of execution of a SELECT query?
Medium
FROM / JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. That is why a column alias from SELECT can be used in ORDER BY but not in WHERE.
8. What are the types of joins?
Easy
INNER — only matching rows. LEFT — all rows of the left table, NULLs where no match. RIGHT — all rows of the right table. FULL OUTER — all rows from both. CROSS — every combination. SELF — a table joined with itself.
9. Write a query to find the second highest salary.
Medium
SELECT MAX(salary) FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
Or with a window function, which also handles the Nth highest:
SELECT DISTINCT salary FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rk FROM employees
) t WHERE rk = 2;
10. Find duplicate emails in a table.
Easy
SELECT email, COUNT(*) AS times
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
11. Delete duplicate rows but keep one.
Hard
DELETE FROM users
WHERE id NOT IN (
SELECT keep_id FROM (SELECT MIN(id) AS keep_id FROM users GROUP BY email) t
);
The extra subquery wrapper is needed in MySQL, which doesn't allow selecting from the table being deleted from.
12. What are aggregate functions?
Easy
Functions that return one value from many rows: COUNT, SUM, AVG, MIN, MAX. Used with GROUP BY to get one result per group. COUNT(*) counts rows; COUNT(col) skips NULLs.
13. What is GROUP BY?
Easy
It puts rows with the same values in the listed columns into groups, so aggregates are calculated per group: SELECT city, AVG(salary) FROM emp GROUP BY city;. Every non-aggregated column in SELECT must be in GROUP BY.
14. What is a subquery? Correlated vs non-correlated?
Medium
A query inside another query. A non-correlated subquery runs once on its own. A correlated subquery refers to the outer row, so it runs once per outer row.
SELECT name FROM emp e
WHERE salary > (SELECT AVG(salary) FROM emp WHERE dept = e.dept);
15. What are window functions?
Hard
Functions that calculate across a set of rows related to the current row without collapsing them into one: ROW_NUMBER(), RANK(), DENSE_RANK(), LAG(), LEAD(), SUM() OVER (...).
SELECT name, dept, salary,
RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rk
FROM emp;
16. ROW_NUMBER vs RANK vs DENSE_RANK?
Medium
For salaries 100, 90, 90, 80: ROW_NUMBER → 1, 2, 3, 4 (always unique). RANK → 1, 2, 2, 4 (skips after ties). DENSE_RANK → 1, 2, 2, 3 (no gaps).
17. Find the top 3 earners in each department.
Hard
SELECT dept, name, salary FROM (
SELECT dept, name, salary,
DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rk
FROM emp
) t
WHERE rk <= 3;
18. What is an index? How does it speed up queries?
Medium
An index is a separate sorted structure (usually a B+ tree) on one or more columns, so the database finds rows without scanning the whole table — like a book index. It speeds up reads on filtered, joined and sorted columns but slows writes and uses space.
19. Clustered vs non-clustered index?
Medium
A clustered index stores the table rows themselves in index order — only one per table (often the primary key). A non-clustered index is a separate structure that points to the rows; a table can have many.
20. When should you not add an index?
Medium
On small tables, on columns with few distinct values (like a gender flag), on columns that change very often, and on tables with heavy writes where read speed doesn't matter. Every index slows INSERT/UPDATE/DELETE.
21. What is normalization?
Medium
Organising tables to reduce duplicate data and update problems. 1NF: atomic values, no repeating groups. 2NF: no partial dependency on part of a composite key. 3NF: no transitive dependency (non-key → non-key). BCNF: every determinant is a candidate key.
22. What is denormalization?
Medium
Deliberately adding redundant data (or combining tables) to make reads faster and avoid joins — common in reporting and high-traffic systems — at the cost of more storage and harder updates.
23. What are ACID properties?
Easy
Atomicity — all or nothing. Consistency — the database moves from one valid state to another. Isolation — concurrent transactions don't interfere. Durability — committed data survives crashes.
24. What is a transaction?
Easy
A group of statements treated as one unit of work. Either all succeed (COMMIT) or none take effect (ROLLBACK) — e.g. debit one account and credit another.
START TRANSACTION;
UPDATE acc SET bal = bal - 500 WHERE id = 1;
UPDATE acc SET bal = bal + 500 WHERE id = 2;
COMMIT;
25. What are the transaction isolation levels?
Hard
Read Uncommitted (dirty reads possible), Read Committed (no dirty reads), Repeatable Read (no non-repeatable reads; MySQL InnoDB default), Serializable (fully isolated, slowest). Higher levels prevent more anomalies but reduce concurrency.
26. What is a view?
Easy
A saved SELECT query used like a virtual table. It simplifies complex queries and can hide columns for security. A materialized view stores the result physically and must be refreshed.
27. What is a stored procedure?
Medium
Precompiled SQL code saved in the database and called by name (CALL get_report(2024)). It can take parameters, contain logic and run several statements — reducing network trips and reusing logic.
28. What is a trigger?
Medium
SQL code that runs automatically BEFORE or AFTER an INSERT, UPDATE or DELETE on a table — e.g. to write an audit log or keep a total updated.
29. UNION vs UNION ALL?
Easy
Both stack the results of two queries with the same columns. UNION removes duplicates (extra sorting work); UNION ALL keeps everything and is faster.
30. CHAR vs VARCHAR?
Easy
CHAR(n) is fixed length — padded with spaces, good for fixed codes like country codes. VARCHAR(n) stores only the actual length plus a small overhead — better for names, emails and other variable text.
31. How do NULLs behave in SQL?
Easy
NULL means unknown, so NULL = NULL is not true. Use IS NULL / IS NOT NULL. Aggregates (except COUNT(*)) ignore NULLs. Replace them with COALESCE(col, 0).
32. What does COALESCE do?
Easy
Returns the first non-NULL value from its arguments: COALESCE(phone, email, 'N/A'). Commonly used to show defaults or to treat missing numbers as 0 in calculations.
33. What is the CASE expression?
Easy
SQL's if/else inside a query.
SELECT name,
CASE WHEN marks >= 75 THEN 'Distinction'
WHEN marks >= 40 THEN 'Pass'
ELSE 'Fail' END AS result
FROM students;
34. What is a self join? Give an example.
Medium
A table joined with itself, using aliases. Example — each employee with their manager's name:
SELECT e.name AS employee, m.name AS manager
FROM emp e LEFT JOIN emp m ON e.manager_id = m.id;
35. Find employees who earn more than their managers.
Medium
SELECT e.name
FROM emp e JOIN emp m ON e.manager_id = m.id
WHERE e.salary > m.salary;
36. Find customers who never placed an order.
Medium
SELECT c.name
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;
Or WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id).
37. What is a CTE?
Medium
A Common Table Expression — a named temporary result defined with WITH, used to make long queries readable. A recursive CTE can walk hierarchies like org charts or categories.
WITH dept_avg AS (
SELECT dept, AVG(salary) AS avg_sal FROM emp GROUP BY dept
)
SELECT * FROM dept_avg WHERE avg_sal > 50000;
38. EXISTS vs IN?
Hard
IN checks a value against a list or subquery result. EXISTS checks whether a subquery returns any row and stops at the first match. EXISTS is often faster for large correlated subqueries; NOT IN gives wrong results when the subquery contains NULLs — prefer NOT EXISTS.
39. What is the difference between a candidate key, super key and composite key?
Medium
A super key is any set of columns that uniquely identifies a row. A candidate key is a minimal super key (no extra columns). The chosen candidate key is the primary key. A composite key is a key made of two or more columns.
40. What are constraints in SQL?
Easy
Rules on columns: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK (e.g. CHECK (age >= 18)) and DEFAULT. They keep data valid at the database level.
41. LIKE and wildcards?
Easy
% matches any number of characters, _ exactly one. WHERE name LIKE 'A%' (starts with A), '%son' (ends with son), '_a%' (second letter a). A leading % usually prevents index use.
42. How do you get the Nth row or paginate results?
Medium
ORDER BY then LIMIT and OFFSET: page 3 with 10 per page is LIMIT 10 OFFSET 20. For deep pages, keyset pagination (WHERE id > last_seen_id ORDER BY id LIMIT 10) is much faster.
43. Count employees in each department, including departments with none.
Medium
SELECT d.name, COUNT(e.id) AS employees
FROM departments d LEFT JOIN emp e ON e.dept_id = d.id
GROUP BY d.name;
COUNT(e.id) gives 0 for empty departments, unlike COUNT(*).
44. Find the running total of sales by date.
Hard
SELECT sale_date, amount,
SUM(amount) OVER (ORDER BY sale_date) AS running_total
FROM sales;
45. What is SQL injection and how do you prevent it?
Medium
An attack where user input changes the meaning of a query, e.g. entering ' OR '1'='1. Prevent it with parameterized queries / prepared statements, an ORM, input validation and a database user with minimal rights. Never build SQL by joining strings.
46. What is a deadlock in a database?
Hard
Two transactions each hold a lock the other needs, so both wait forever. The database detects it and rolls one back. Reduce it by accessing tables in the same order, keeping transactions short and using proper indexes.
47. SQL vs NoSQL?
Easy
SQL databases have fixed schemas, tables, joins and strong ACID transactions — great for structured, related data. NoSQL (MongoDB, Redis, Cassandra) has flexible schemas and scales horizontally more easily — good for huge, fast-changing or unstructured data.
48. What is the difference between DISTINCT and GROUP BY?
Easy
DISTINCT just removes duplicate rows from the result. GROUP BY groups rows so you can calculate aggregates per group. SELECT DISTINCT dept FROM emp and SELECT dept FROM emp GROUP BY dept return the same list.
49. What is a composite index and why does column order matter?
Hard
An index on several columns, e.g. (city, age). It works like a phone book sorted by city, then age — so it helps queries filtering on city, or on city and age, but not on age alone (the leftmost prefix rule). Put the most frequently filtered, most selective column first.
50. How would you optimize a slow query?
Hard
Check the plan with EXPLAIN, add indexes on filtered/joined columns, select only needed columns (no SELECT *), avoid functions on indexed columns in WHERE, replace correlated subqueries with joins, paginate, and cache repeated results.
More topics
- C++ interview questions (50)
- Computer Networks interview questions (50)
- DBMS interview questions (50)
- DSA interview questions (50)
- HR Round interview questions (50)
- Java interview questions (50)
- JavaScript interview questions (50)
- OOP interview questions (50)
- Operating Systems interview questions (50)
- Python interview questions (50)
- React & Node.js interview questions (50)
- SQL interview questions (50)
- System Design interview questions (50)