Quick answer: These 82 SQL interview questions and answers cover what is asked most in data analyst, database developer, back-end developer and software engineer roles: SQL basics, keys and constraints, querying, joins, subqueries and CTEs, window functions, transactions, normalization, indexes and performance, stored procedures and security, plus the most common query-writing questions. Key answers include short code examples.
Read each answer, then close the page and explain it aloud in two or three sentences. That is exactly what interviewers check.
Contents
- SQL Basics
- Keys and Constraints
- Querying Data
- Joins
- Subqueries, CTEs and Views
- Window Functions
- Modifying Data and Transactions
- Normalization and Database Design
- Indexes and Performance
- Stored Procedures, Triggers and Security
- SQL vs NoSQL and Common Interview Queries
- How to prepare
- FAQs
1. SQL Basics Interview Questions
Q1. What is SQL?
SQL (Structured Query Language) is the standard language for working with relational databases. You use it to create tables, insert and update data, query it with SELECT and control access. MySQL, PostgreSQL, SQL Server and Oracle all use SQL, with small differences in syntax.
Q2. What is the difference between SQL and MySQL?
SQL is the language; MySQL is a database management system (RDBMS) that understands SQL. In the same way, PostgreSQL, Oracle and SQL Server are other database systems that also use SQL.
Q3. What is a database and what is an RDBMS?
A database is an organised collection of data. An RDBMS (Relational Database Management System) stores that data in tables of rows and columns and lets you link tables through keys. It also enforces rules such as data types, constraints and transactions.
Q4. What are the types of SQL commands?
SQL commands fall into five groups: DDL (CREATE, ALTER, DROP, TRUNCATE) defines structure; DML (INSERT, UPDATE, DELETE) changes data; DQL (SELECT) reads data; DCL (GRANT, REVOKE) controls permissions; and TCL (COMMIT, ROLLBACK, SAVEPOINT) manages transactions.
Q5. What is a table, a row and a column?
A table stores data about one kind of entity, such as students. Each row (record) is one student, and each column (field) is one attribute, such as name or marks. Every column has a fixed data type.
Q6. What are common SQL data types?
Common types are INT and BIGINT for whole numbers, DECIMAL(p,s) for exact money values, FLOAT for approximate numbers, CHAR(n) for fixed-length text, VARCHAR(n) for variable text, DATE, TIME and TIMESTAMP for dates, and BOOLEAN. Choosing the right type saves space and prevents bad data.
Q7. What is the difference between CHAR and VARCHAR?
CHAR(n) always stores exactly n characters and pads shorter values with spaces, so it suits fixed-length codes like country codes. VARCHAR(n) stores only the characters entered, up to n, so it saves space for names and addresses.
Q8. What is NULL in SQL?
NULL means a value is unknown or missing. It is not zero and not an empty string. You must test it with IS NULL or IS NOT NULL, because NULL = NULL is not true.
SELECT name FROM students
WHERE phone IS NULL;2. Keys and Constraints Interview Questions
Q9. What is a primary key?
A primary key is a column, or a set of columns, that uniquely identifies each row. It cannot contain duplicates or NULL values, and a table can have only one primary key.
Q10. What is a foreign key?
A foreign key is a column in one table that refers to the primary key of another table. It links the two tables and stops you inserting a child row that points to a parent that does not exist.
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);Q11. What is the difference between a primary key and a unique key?
Both prevent duplicate values. A table can have only one primary key and it cannot be NULL, while it can have many unique keys and a unique column usually allows NULL values.
Q12. What is a composite key?
A composite key is a primary key made of two or more columns whose combination is unique. For example, (student_id, course_id) in an enrolment table, where a student can take many courses but each course only once.
Q13. What are candidate keys and super keys?
A super key is any set of columns that uniquely identifies a row. A candidate key is a minimal super key with no extra columns. One candidate key is chosen as the primary key and the others become alternate keys.
Q14. What is a constraint? Name the common ones.
A constraint is a rule the database enforces on data. Common constraints are NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK (for example marks between 0 and 100) and DEFAULT (a value used when none is supplied).
Q15. What does ON DELETE CASCADE do?
On a foreign key, ON DELETE CASCADE automatically deletes child rows when the parent row is deleted. For example, deleting a customer also deletes their orders. Use it carefully, because one delete can remove a lot of data.
3. Querying Data Interview Questions
Q16. What is the order of execution of a SELECT query?
Although we write SELECT first, the database processes clauses in this order: FROM and JOINs, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, and finally LIMIT. This explains why you cannot use a SELECT alias inside WHERE.
Q17. What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping, so it cannot use aggregate functions. HAVING filters groups after GROUP BY, so it is used with aggregates such as COUNT or SUM.
SELECT dept, COUNT(*) AS staff
FROM employees
WHERE status = 'active'
GROUP BY dept
HAVING COUNT(*) > 5;Q18. What does GROUP BY do?
GROUP BY collects rows with the same value in one or more columns into a single group, so that aggregate functions can be calculated for each group. For example, total sales per city.
Q19. What are aggregate functions?
Aggregate functions calculate one value from many rows: COUNT, SUM, AVG, MIN and MAX. Except for COUNT(*), they ignore NULL values.
Q20. What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?
COUNT(*) counts all rows. COUNT(column) counts rows where that column is not NULL. COUNT(DISTINCT column) counts unique non-NULL values.
Q21. What is the use of DISTINCT?
DISTINCT removes duplicate rows from the result. SELECT DISTINCT city FROM customers returns each city only once.
Q22. How do LIKE and wildcards work?
LIKE matches text patterns. % matches any number of characters and _ matches exactly one character. For example, LIKE 'S%' finds names starting with S and LIKE '_a%' finds names whose second letter is a.
Q23. What is the difference between IN, BETWEEN and EXISTS?
IN checks whether a value is in a list or subquery result. BETWEEN checks an inclusive range, such as salary BETWEEN 30000 AND 50000. EXISTS returns true if a subquery returns at least one row, and it is often faster for large correlated checks.
Q24. How do you sort and limit results?
ORDER BY sorts results in ascending (ASC, the default) or descending (DESC) order. LIMIT in MySQL and PostgreSQL, TOP in SQL Server, or FETCH FIRST n ROWS ONLY in standard SQL returns only the first rows.
SELECT name, salary FROM employees
ORDER BY salary DESC
LIMIT 5;Q25. What is an alias in SQL?
An alias is a temporary name for a column or table, created with AS. It makes results readable and queries shorter, for example SELECT e.name FROM employees AS e.
Q26. What does the CASE expression do?
CASE adds if-else logic inside a query and returns a value based on conditions.
SELECT name,
CASE WHEN marks >= 75 THEN 'Distinction'
WHEN marks >= 40 THEN 'Pass'
ELSE 'Fail' END AS result
FROM students;Q27. What do COALESCE and NULLIF do?
COALESCE returns the first non-NULL value from its arguments, for example COALESCE(phone, 'Not given'). NULLIF(a, b) returns NULL if a equals b, which is useful to avoid divide-by-zero errors, as in total / NULLIF(count, 0).
4. Joins Interview Questions
Q28. What is a JOIN?
A JOIN combines rows from two or more tables based on a related column, usually a primary key and foreign key. It lets you answer questions that need data from several tables, such as customer names with their orders.
Q29. What are the types of joins?
INNER JOIN returns only matching rows. LEFT JOIN returns all rows from the left table plus matches, with NULLs where there is no match. RIGHT JOIN does the same for the right table. FULL OUTER JOIN returns all rows from both tables. CROSS JOIN returns every combination of rows. A SELF JOIN joins a table to itself.
Q30. What is the difference between INNER JOIN and LEFT JOIN?
INNER JOIN keeps only customers who have orders. LEFT JOIN keeps every customer, and shows NULL order columns for customers with no orders.
SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;Q31. How do you find rows in one table that have no match in another?
Use a LEFT JOIN and keep rows where the right side is NULL, or use NOT EXISTS.
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;Q32. What is a self join? Give an example.
A self join joins a table to itself using aliases. A classic example is listing each employee with their manager, where manager_id refers to another row in the same employees table.
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.emp_id;Q33. What is a CROSS JOIN?
A CROSS JOIN returns the Cartesian product: every row of the first table combined with every row of the second. Two tables of 10 and 5 rows give 50 rows. It is useful for generating combinations, such as all sizes for all colours.
Q34. What is the difference between UNION and UNION ALL?
Both stack the results of two queries with the same number and type of columns. UNION removes duplicates, which needs extra sorting work. UNION ALL keeps duplicates and is faster.
Q35. What is the difference between a JOIN and a UNION?
A JOIN combines columns from different tables side by side using a matching condition. A UNION combines rows from two queries one below the other.
5. Subqueries, CTEs and Views Interview Questions
Q36. What is a subquery?
A subquery is a query inside another query, in WHERE, FROM or SELECT. For example, finding employees who earn more than the average salary.
SELECT name, salary FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);Q37. What is a correlated subquery?
A correlated subquery uses a value from the outer query, so it runs once for each outer row. For example, finding employees who earn more than the average of their own department.
Q38. What is a CTE (Common Table Expression)?
A CTE is a named temporary result set defined with WITH, used in the query that follows. It makes long queries easier to read than nested subqueries, and recursive CTEs can walk hierarchies such as organisation charts.
WITH dept_avg AS (
SELECT dept, AVG(salary) AS avg_sal
FROM employees GROUP BY dept
)
SELECT e.name, e.dept, e.salary
FROM employees e JOIN dept_avg d ON e.dept = d.dept
WHERE e.salary > d.avg_sal;Q39. What is a view?
A view is a saved SELECT query that behaves like a virtual table. It hides complex joins, shows users only the columns they need, and adds a layer of security. A normal view stores no data of its own.
Q40. What is a materialized view?
A materialized view stores the query result physically, so reads are fast, but it must be refreshed when the base data changes. It suits reports and dashboards over large tables.
Q41. Can you update data through a view?
Simple views based on one table, without GROUP BY, DISTINCT or aggregates, are usually updatable. Views with joins or aggregates are generally read-only unless the database supports special triggers.
6. Window Functions Interview Questions
Q42. What are window functions?
Window functions calculate a value for each row using a set of related rows (the window), without collapsing rows like GROUP BY does. They use the OVER clause, with optional PARTITION BY and ORDER BY.
Q43. What is the difference between ROW_NUMBER, RANK and DENSE_RANK?
For salaries 900, 800, 800, 700: ROW_NUMBER gives 1, 2, 3, 4; RANK gives 1, 2, 2, 4 (it skips after a tie); DENSE_RANK gives 1, 2, 2, 3 (no gaps).
Q44. How do you find the second highest salary?
A simple way is a subquery with MAX. DENSE_RANK works for the Nth highest salary and handles ties.
-- Second highest
SELECT MAX(salary) FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
-- Nth highest (N = 3)
SELECT DISTINCT salary FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees) t
WHERE rnk = 3;Q45. How do you find the highest-paid employee in each department?
Rank employees within each department with PARTITION BY and keep rank 1.
SELECT dept, name, salary FROM (
SELECT dept, name, salary,
RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rnk
FROM employees) t
WHERE rnk = 1;Q46. What do LAG and LEAD do?
LAG reads a value from a previous row and LEAD from a following row in the window. They are used for month-on-month change, such as sales minus LAG(sales) OVER (ORDER BY month).
Q47. How do you calculate a running total?
Use SUM as a window function ordered by date.
SELECT order_date, amount,
SUM(amount) OVER (ORDER BY order_date) AS running_total
FROM orders;7. Modifying Data and Transactions Interview Questions
Q48. What is the difference between DELETE, TRUNCATE and DROP?
DELETE removes selected rows using WHERE, fires triggers and can be rolled back inside a transaction. TRUNCATE removes all rows quickly and resets identity counters, but keeps the table structure. DROP removes the whole table, including its structure. Whether TRUNCATE can be rolled back depends on the database: PostgreSQL and SQL Server allow it inside a transaction, MySQL does not.
Q49. How do you update rows using another table?
Join the target table to the source table in the UPDATE. The syntax varies a little between databases; this is MySQL.
UPDATE employees e
JOIN departments d ON e.dept_id = d.dept_id
SET e.location = d.location;Q50. How do you delete duplicate rows but keep one?
Number the duplicates with ROW_NUMBER and delete every row after the first. This form works in PostgreSQL and SQL Server; in MySQL, wrap the inner query in a derived table.
WITH d AS (
SELECT id, ROW_NUMBER() OVER (
PARTITION BY email ORDER BY id) AS rn
FROM users)
DELETE FROM users WHERE id IN (SELECT id FROM d WHERE rn > 1);Q51. How do you find duplicate records?
Group by the columns that should be unique and keep groups with more than one row.
SELECT email, COUNT(*) AS times
FROM users
GROUP BY email
HAVING COUNT(*) > 1;Q52. What is a transaction?
A transaction is a group of SQL statements that must all succeed or all fail together. A bank transfer is the classic example: the debit and the credit must both happen, or neither. COMMIT saves the changes and ROLLBACK undoes them.
Q53. What are the ACID properties?
Atomicity: all or nothing. Consistency: data moves from one valid state to another. Isolation: concurrent transactions do not interfere. Durability: committed changes survive crashes.
Q54. What is a SAVEPOINT?
A SAVEPOINT marks a point inside a transaction so you can roll back part of the work without cancelling the whole transaction, using ROLLBACK TO savepoint_name.
Q55. What are transaction isolation levels?
From weakest to strongest: READ UNCOMMITTED (dirty reads possible), READ COMMITTED (default in many databases), REPEATABLE READ (default in MySQL InnoDB) and SERIALIZABLE (fully isolated but slowest). Higher levels prevent more anomalies but reduce concurrency.
Q56. What are dirty reads, non-repeatable reads and phantom reads?
A dirty read sees another transaction's uncommitted change. A non-repeatable read gets a different value when reading the same row twice. A phantom read finds new rows appearing when the same range query is run twice.
Q57. What is a deadlock?
A deadlock happens when two transactions each hold a lock the other needs, so both wait forever. The database detects it and rolls one back. Accessing tables in the same order and keeping transactions short reduce deadlocks.
8. Normalization and Database Design Interview Questions
Q58. What is normalization?
Normalization is organising tables to reduce duplicate data and avoid update, insert and delete anomalies. You split data into related tables linked by keys.
Q59. Explain 1NF, 2NF and 3NF.
1NF: every column holds a single atomic value and there are no repeating groups. 2NF: in 1NF and no non-key column depends on only part of a composite key. 3NF: in 2NF and no non-key column depends on another non-key column (no transitive dependency).
Q60. What is BCNF?
Boyce-Codd Normal Form is a stricter version of 3NF: for every functional dependency X → Y, X must be a super key. It removes some anomalies that 3NF still allows.
Q61. What is denormalization and when is it used?
Denormalization deliberately adds redundant data, such as storing a customer name in the orders table, to avoid expensive joins. It is used in reporting and read-heavy systems where speed matters more than storage.
Q62. What are one-to-one, one-to-many and many-to-many relationships?
One-to-one: one person has one passport. One-to-many: one customer has many orders, implemented with a foreign key on the many side. Many-to-many: students and courses, implemented with a junction table such as enrolments.
Q63. What is an ER diagram?
An Entity-Relationship diagram shows entities (tables), their attributes (columns) and the relationships between them. It is drawn before creating tables to plan the database design.
9. Indexes and Performance Interview Questions
Q64. What is an index?
An index is a separate data structure, usually a B-tree, that lets the database find rows without scanning the whole table, like the index at the back of a book. It speeds up SELECT queries but slows INSERT, UPDATE and DELETE slightly and uses extra storage.
Q65. What is the difference between clustered and non-clustered indexes?
A clustered index decides the physical order of rows in the table, so a table can have only one (often the primary key). A non-clustered index is a separate structure that points to the rows, and a table can have many.
Q66. When should you not create an index?
Avoid indexes on small tables, on columns with very few distinct values (such as gender), and on tables with very heavy writes. Too many indexes slow down every insert and update.
Q67. What is a composite index and why does column order matter?
A composite index covers several columns, such as (city, age). It helps queries that filter on city, or on city and age, but usually not on age alone, because the index is sorted by the first column first (the leftmost prefix rule).
Q68. How do you find why a query is slow?
Run EXPLAIN (or EXPLAIN ANALYZE) to see the execution plan: whether it uses an index or a full table scan, the join order and the estimated rows. Then add suitable indexes, rewrite the query or reduce the data it reads.
Q69. How can you optimise a slow SQL query?
Select only the columns you need instead of SELECT *, index columns used in WHERE and JOIN, avoid functions on indexed columns in WHERE, replace large IN subqueries with JOIN or EXISTS, filter early, and paginate large results.
Q70. What is partitioning?
Partitioning splits a very large table into smaller pieces, for example by month, while it still looks like one table. Queries that filter on the partition key read only the relevant partitions, and old partitions can be dropped quickly.
10. Stored Procedures, Triggers and Security Interview Questions
Q71. What is a stored procedure?
A stored procedure is a saved set of SQL statements that can accept parameters and is executed with CALL or EXEC. It reduces network traffic, reuses logic and can be given separate permissions.
Q72. What is the difference between a stored procedure and a function?
A function must return a value and can be used inside SELECT, but usually cannot change data. A stored procedure may return zero or more values, can change data and manage transactions, but cannot be used inside SELECT.
Q73. What is a trigger?
A trigger is SQL code that runs automatically BEFORE or AFTER an INSERT, UPDATE or DELETE on a table. It is used for audit logs and validation, but too many triggers make behaviour hard to follow.
Q74. What is a cursor?
A cursor lets you process a query result one row at a time inside a procedure. It is slow compared to set-based SQL, so it should be used only when row-by-row logic is truly needed.
Q75. What is SQL injection and how do you prevent it?
SQL injection happens when user input is added directly into a query string, letting an attacker change the query, for example by typing ' OR '1'='1. Prevent it with parameterised queries or prepared statements, input validation and least-privilege database accounts.
Q76. What do GRANT and REVOKE do?
GRANT gives a user permissions, such as SELECT or INSERT on a table. REVOKE takes them back. Following least privilege, application accounts should get only the permissions they need.
11. SQL vs NoSQL and Common Interview Queries Interview Questions
Q77. What is the difference between SQL and NoSQL databases?
SQL databases store structured data in tables with a fixed schema and support joins and ACID transactions. NoSQL databases (document, key-value, column or graph stores such as MongoDB and Redis) have flexible schemas and scale out easily, which suits large or changing data.
Q78. What is the difference between OLTP and OLAP?
OLTP systems handle many small, fast transactions, such as bank transfers or orders. OLAP systems handle large analytical queries over historical data, such as yearly sales reports in a data warehouse.
Q79. How do you get the number of employees in each department, including empty departments?
Start from departments and LEFT JOIN employees, so departments with no staff show 0.
SELECT d.dept_name, COUNT(e.emp_id) AS staff
FROM departments d
LEFT JOIN employees e ON e.dept_id = d.dept_id
GROUP BY d.dept_name;Q80. How do you find employees who earn more than their manager?
Self join employees to their managers and compare salaries.
SELECT e.name
FROM employees e
JOIN employees m ON e.manager_id = m.emp_id
WHERE e.salary > m.salary;Q81. How do you get the top 3 products by sales in each category?
Rank products inside each category and keep the first three.
SELECT * FROM (
SELECT category, product, sales,
DENSE_RANK() OVER (PARTITION BY category ORDER BY sales DESC) AS rnk
FROM product_sales) t
WHERE rnk <= 3;Q82. How do you find customers who placed orders in every month of a year?
Count distinct months per customer and keep customers with 12 (MySQL date functions shown).
SELECT customer_id
FROM orders
WHERE YEAR(order_date) = 2025
GROUP BY customer_id
HAVING COUNT(DISTINCT MONTH(order_date)) = 12;How to Prepare for a SQL Interview
- Write queries by hand: practise on a simple employees, departments and orders schema until joins and GROUP BY feel natural.
- Explain your logic: say which tables you join, how you filter and how you handle NULLs and duplicates.
- Know the classics: second highest salary, duplicates, top N per group, employees earning more than their manager.
- Learn window functions: ROW_NUMBER, RANK and running totals are now standard for analyst interviews.
- Mention performance: indexes, EXPLAIN and avoiding SELECT * show real-world understanding.
Next steps: combine SQL with Python interview questions, build portfolio work from our data science projects, and revise problem solving with DSA interview questions.
More interview preparation: see all interview questions, including Python, SQL, SQL query, Java, JavaScript, React, C++, .NET, Spring Boot, Node.js, DSA, OOPs, DBMS, operating system, networking, machine learning, data science, AI, Excel, Power BI, DevOps, manual testing, Selenium, cyber security and HR.
Frequently Asked Questions
Which SQL topics are most important for freshers?
Joins, GROUP BY with HAVING, subqueries, keys and constraints, normalization, and the second-highest-salary type of query come up in almost every fresher interview. For data analyst roles, add window functions and CTEs.
Is SQL enough to get a job?
SQL alone is enough for some entry-level database and reporting roles, but most jobs combine it with Excel, Python or a BI tool for analysts, or with a programming language for developers.
Which database should I practise SQL on?
MySQL and PostgreSQL are both free and widely used. The core SQL you learn on one works on the others with small syntax changes, such as LIMIT versus TOP.
How should I prepare for an SQL interview?
Learn the concepts on this page, then write queries by hand on a sample employees–departments–orders schema every day. Practise explaining your query step by step, including how you handle NULLs and duplicates.