{jsonbody.com}

Top 40 SQL Interview Questions & Answers

Top 40 SQL interview questions and answers for freshers and experienced developers: joins, keys, GROUP BY, window functions, indexes and normalization.

Loading…

SQL Basics & Keys

Q1. What is SQL?

Structured Query Language, the standard language for creating, reading, updating and deleting data in relational databases such as MySQL, PostgreSQL, SQL Server and Oracle.

Q2. What are DDL, DML, DCL and TCL?

DDL defines structure (CREATE, ALTER, DROP). DML changes data (INSERT, UPDATE, DELETE, and SELECT is often included). DCL controls access (GRANT, REVOKE). TCL manages transactions (COMMIT, ROLLBACK).

Q3. What is a primary key?

A column or set of columns that uniquely identifies each row. It cannot be NULL, and a table has only one.

Q4. What is a foreign key?

A column that refers to the primary key of another table. It enforces referential integrity, so you cannot add an order for a customer that does not exist.

Q5. What is the difference between a primary key and a unique key?

Both enforce uniqueness. A table has one primary key, which cannot be NULL. It can have many unique keys, which usually allow NULL.

Q6. What is the difference between DELETE, TRUNCATE and DROP?

DELETE removes chosen rows, can use WHERE and is logged row by row. TRUNCATE quickly removes all rows and keeps the table. DROP removes the table itself.

Q7. What are constraints?

Rules on columns: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK and DEFAULT. They keep invalid data out of the database.

Q8. How does NULL work in SQL?

NULL means unknown. Comparing anything to NULL with = gives unknown, so use IS NULL or IS NOT NULL. Aggregates like SUM ignore NULLs.

Q9. What is the difference between CHAR and VARCHAR?

CHAR(n) is fixed length and padded with spaces. VARCHAR(n) stores only the characters used, up to n, so it suits text of varying length.

Q10. What is the order of execution of a SELECT query?

FROM and JOIN, then WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and finally LIMIT. That is why WHERE cannot use column aliases from SELECT.

Joins, Grouping & Subqueries

Q11. What are the types of joins?

INNER JOIN returns matching rows from both tables. LEFT JOIN returns all left rows with matches or NULLs. RIGHT JOIN does the reverse. FULL OUTER JOIN returns all rows from both. CROSS JOIN returns every combination.

Q12. What is a self join?

A table joined to itself with two aliases, such as finding each employee's manager from the same employees table.

Q13. What is the difference between WHERE and HAVING?

WHERE filters rows before grouping. HAVING filters groups after GROUP BY, so it can use aggregates such as HAVING COUNT(*) > 5.

Q14. What does GROUP BY do?

It collapses rows with the same values into one row per group, so aggregate functions such as COUNT, SUM and AVG compute a value per group.

Q15. What is the difference between UNION and UNION ALL?

UNION combines results and removes duplicates. UNION ALL keeps duplicates and is faster because it skips that step.

Q16. What is a subquery?

A query inside another query, used in WHERE, FROM or SELECT. A correlated subquery refers to the outer query and runs once per outer row.

Q17. What is the difference between IN and EXISTS?

IN checks a value against a list or subquery result. EXISTS checks whether a subquery returns any row and stops at the first match. NOT IN returns nothing if the list contains a NULL, while NOT EXISTS behaves as expected.

Q18. What is a CTE?

A Common Table Expression, defined with WITH name AS (...), is a named temporary result used in the next query. It makes complex queries readable, and recursive CTEs walk hierarchies.

Q19. How do you find duplicate rows?

Group by the columns that should be unique and keep groups with more than one row: SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1.

Q20. How do you find the second highest salary?

SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees), or use DENSE_RANK() and pick rank 2, which also generalises to the Nth highest.

Window Functions & Advanced Queries

Q21. What are window functions?

Functions that compute a value across rows related to the current row without collapsing them, using OVER (PARTITION BY ... ORDER BY ...). Examples are running totals and rankings.

Q22. What is the difference between ROW_NUMBER, RANK and DENSE_RANK?

For ties, ROW_NUMBER gives unique numbers (1, 2, 3), RANK gives equal ranks and skips (1, 1, 3), and DENSE_RANK gives equal ranks without gaps (1, 1, 2).

Q23. What do LAG and LEAD do?

They read a value from a previous or next row in the window, which suits comparing each month with the last.

Q24. How do you calculate a running total?

SUM(amount) OVER (ORDER BY order_date) adds up all rows up to the current one in date order. Add PARTITION BY customer_id to restart it per customer.

Q25. How do you get the top N rows per group?

Number rows per group with ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) in a subquery or CTE, then keep rows where the number is at most N.

Q26. What is a CASE expression?

SQL's if-else: CASE WHEN score >= 90 THEN 'A' WHEN score >= 75 THEN 'B' ELSE 'C' END. It works in SELECT, ORDER BY and inside aggregates.

Q27. What is a view?

A saved query that behaves like a virtual table. It simplifies complex queries and can limit which columns users see. A materialized view stores the result and must be refreshed.

Q28. What is a stored procedure?

Precompiled SQL code stored in the database and called by name, with parameters. It keeps logic near the data, but can be harder to version and test.

Q29. What is a trigger?

Code that runs automatically on INSERT, UPDATE or DELETE on a table, for example to write audit logs. Overusing triggers hides logic and slows writes.

Q30. How do you delete duplicate rows but keep one?

Number duplicates with ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) and delete rows where the number is greater than 1.

Indexes, Normalization & Transactions

Q31. What is an index?

A data structure, usually a B-tree, that lets the database find rows without scanning the whole table. It speeds up reads but slows writes and uses storage.

Q32. What is the difference between clustered and non-clustered indexes?

A clustered index sets the physical order of rows, so a table has only one, usually the primary key. A non-clustered index is a separate structure that points to the rows.

Q33. What is a composite index, and why does column order matter?

An index on several columns, such as (last_name, first_name). It is used for queries filtering on the leading columns, so put the most selective or most used column first.

Q34. When does an index not help?

On small tables, columns with very few distinct values, queries that wrap the column in a function like LOWER(email), and LIKE '%term' with a leading wildcard.

Q35. What is normalization?

Organising tables to reduce duplicate data. 1NF needs atomic values, 2NF removes partial dependencies on a composite key, and 3NF removes dependencies between non-key columns.

Q36. What is denormalization?

Adding redundant data on purpose, such as storing a total on an order, to speed up reads at the cost of extra work keeping copies in sync.

Q37. What are ACID properties?

Atomicity: all or nothing. Consistency: rules always hold. Isolation: concurrent transactions do not interfere. Durability: committed data survives crashes.

Q38. What are transaction isolation levels?

Read Uncommitted, Read Committed, Repeatable Read and Serializable, from weakest to strongest. Higher levels prevent more anomalies such as dirty reads and phantom reads but allow less concurrency.

Q39. What is a deadlock in a database?

Two transactions each hold a lock the other needs. The database detects this and rolls one back. Access tables in a consistent order and keep transactions short to avoid it.

Q40. How do you optimise a slow query?

Read its plan with EXPLAIN, add or fix indexes, select only needed columns, avoid functions on indexed columns, rewrite heavy subqueries as joins, and paginate large results.