🎯 Recommended Products for Students & Parents
Handpicked products specially selected for our visitors.
School Backpack Combo
✔ 29 L Spacious Backpack
✔ Includes Tiffin & Pouch
✔ Perfect for School & Coaching
Niacinamide Bright & Clear Skin Combo
✔ Brightens Skin
✔ Reduces Acne Marks
✔ Suitable for Daily Skincare
Disclosure: Some links on this page are affiliate links. We may earn a small commission if you purchase through them, at no additional cost to you.
Preparing for an SQL interview?
Whether you are a fresher, SQL developer, software developer, data analyst, QA engineer, business analyst, or experienced database professional, SQL is an important skill to prepare.
This guide covers 75+ SQL interview questions and answers, starting with basic SQL concepts and moving toward joins, aggregate functions, subqueries, CTEs, window functions, indexes, transactions, normalization, and practical SQL coding problems.
The goal is not just to memorize answers. You should understand why a query works, how SQL processes data, and when to use each SQL feature.

SQL Interview Questions
Table of Contents
- What is SQL?
- Why is SQL important in interviews?
- Basic SQL Interview Questions
- SQL Commands and Constraints
- SQL JOIN Interview Questions
- GROUP BY, HAVING and Aggregate Functions
- Subquery and CTE Questions
- SQL Window Function Questions
- Practical SQL Query Interview Questions
- Database Design and Normalization
- Index and Performance Questions
- Transactions and ACID Questions
- Advanced SQL Interview Questions
- Tricky SQL Interview Questions
- SQL Interview Questions for Freshers
- SQL Interview Questions for Experienced Candidates
- SQL Interview Preparation Tips
- Frequently Asked Questions

1. What Is SQL?
SQL (Structured Query Language) is a language used to communicate with relational databases.
SQL can be used to:
- Create databases and tables
- Insert data
- Retrieve data
- Update data
- Delete data
- Filter records
- Sort data
- Join multiple tables
- Group and summarize data
- Create views
- Manage transactions
- Analyze data
For example:
SELECT name, salary
FROM employees
WHERE salary > 50000;
This query returns employees whose salary is greater than 50,000.
2. Why Is SQL Important in Interviews?
SQL interviews usually test two different abilities:
Conceptual knowledge
For example:
- What is a primary key?
- What is normalization?
- What is an index?
- What is a JOIN?
- What is a transaction?
Practical problem-solving
For example:
- Find the second-highest salary.
- Find duplicate records.
- Find employees who do not belong to any department.
- Find the highest-paid employee in each department.
- Calculate a running total.
- Find the top three employees in each department.
Modern SQL interview preparation increasingly includes window functions, CTEs, subqueries, JOINs and practical query-writing, rather than only definitions.
Part 1: Basic SQL Interview Questions
3. What is a Database?
A database is an organized collection of data that can be stored, accessed, managed and updated electronically.
Examples include:
- MySQL
- PostgreSQL
- Microsoft SQL Server
- Oracle Database
- SQLite
4. What is a DBMS?
DBMS stands for Database Management System.
It is software used to create, manage and interact with databases.
Examples:
- MySQL
- Oracle
- PostgreSQL
- Microsoft SQL Server
5. What is an RDBMS?
RDBMS stands for Relational Database Management System.
An RDBMS stores data primarily in tables consisting of rows and columns and provides relationships between tables.
Examples:
- MySQL
- PostgreSQL
- Oracle
- SQL Server
6. What is a Table in SQL?
A table stores data in rows and columns.
Example:
| id | name | salary |
|---|---|---|
| 1 | Amit | 45000 |
| 2 | Priya | 60000 |
| 3 | Rahul | 52000 |
Here:
id,name, andsalaryare columns.- Each employee record is a row.
7. What is a Primary Key?
A primary key uniquely identifies each row in a table.
Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(100),
salary DECIMAL(10,2)
);
employee_id uniquely identifies each employee.
A primary key:
- Must be unique
- Cannot contain
NULL - Identifies a record
8. What is a Foreign Key?
A foreign key creates a relationship between tables.
Example:
CREATE TABLE departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(100)
);
Another table can reference it:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(100),
department_id INT,
FOREIGN KEY (department_id)
REFERENCES departments(department_id)
);
9. What is a UNIQUE Constraint?
A UNIQUE constraint prevents duplicate values in a column or group of columns.
Example:
CREATE TABLE users (
id INT PRIMARY KEY,
email VARCHAR(150) UNIQUE
);
Two users cannot have the same email value.
10. What is a NOT NULL Constraint?
NOT NULL prevents a column from containing NULL.
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
Part 2: SQL Commands
11. What are DDL, DML, DQL, DCL and TCL?
SQL commands are commonly grouped into several categories.
DDL – Data Definition Language
Used to define database structures.
Examples:
CREATE
ALTER
DROP
TRUNCATE
DML – Data Manipulation Language
Used to modify data.
INSERT
UPDATE
DELETE
DQL – Data Query Language
Primarily used to retrieve data.
SELECT
DCL – Data Control Language
Used for permissions.
GRANT
REVOKE
TCL – Transaction Control Language
Used to manage transactions.
COMMIT
ROLLBACK
SAVEPOINT
Part 3: DELETE vs TRUNCATE vs DROP
12. What is the difference between DELETE, TRUNCATE and DROP?
| Command | Purpose |
|---|---|
| DELETE | Removes rows |
| TRUNCATE | Removes all rows from a table |
| DROP | Removes the table itself |
DELETE
DELETE FROM employees
WHERE department_id = 5;
You can use a WHERE condition with DELETE.
TRUNCATE
TRUNCATE TABLE employees;
It removes all rows from the table.
DROP
DROP TABLE employees;
This removes the table definition and its data.
Interview tip: The exact transaction, logging, identity-reset and trigger behavior of TRUNCATE can vary by database system, so answer according to the SQL engine being discussed.
Part 4: SELECT, WHERE and ORDER BY
13. How do you retrieve all records from a table?
SELECT *
FROM employees;
14. How do you select specific columns?
SELECT name, salary
FROM employees;
15. How do you filter records?
Use the WHERE clause.
SELECT *
FROM employees
WHERE salary > 50000;
16. How do you sort records?
Use ORDER BY.
SELECT *
FROM employees
ORDER BY salary DESC;
ASC means ascending.
DESC means descending.
Part 5: WHERE vs HAVING
17. What is the difference between WHERE and HAVING?
This is one of the most common SQL interview questions.
WHERE
Filters individual rows before grouping.
SELECT *
FROM employees
WHERE salary > 50000;
HAVING
Filters groups after aggregation.
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING AVG(salary) > 50000;
Easy way to remember
WHERE → filters rows
HAVING → filters groups
Part 6: GROUP BY and Aggregate Functions
18. What is GROUP BY?
GROUP BY combines rows having the same value so that aggregate calculations can be performed.
Example:
SELECT department_id, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id;
19. What are aggregate functions?
Common aggregate functions include:
COUNT()SUM()AVG()MIN()MAX()
Example:
SELECT
COUNT(*) AS total_employees,
AVG(salary) AS average_salary,
MAX(salary) AS highest_salary,
MIN(salary) AS lowest_salary
FROM employees;
Part 7: SQL JOIN Interview Questions
JOINs are among the most important SQL interview topics because they test whether you understand relationships between tables.
20. What is an INNER JOIN?
An INNER JOIN returns rows where matching records exist in both tables.
SELECT
e.name,
d.department_name
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id;
21. What is a LEFT JOIN?
A LEFT JOIN returns all rows from the left table and matching rows from the right table.
If no match exists, columns from the right table generally contain NULL.
SELECT
e.name,
d.department_name
FROM employees e
LEFT JOIN departments d
ON e.department_id = d.department_id;
22. What is a RIGHT JOIN?
A RIGHT JOIN returns all rows from the right table and matching rows from the left table.
SELECT
e.name,
d.department_name
FROM employees e
RIGHT JOIN departments d
ON e.department_id = d.department_id;
23. What is a FULL OUTER JOIN?
A FULL OUTER JOIN returns matching rows plus unmatched rows from both tables.
Conceptually:
SELECT *
FROM employees e
FULL OUTER JOIN departments d
ON e.department_id = d.department_id;
Support for FULL OUTER JOIN differs between database systems, so always consider the SQL dialect.
24. What is a CROSS JOIN?
A CROSS JOIN produces the Cartesian product of two tables.
If table A contains 3 rows and table B contains 4 rows, the result can contain:
3 × 4 = 12 rows
Example:
SELECT *
FROM colors
CROSS JOIN sizes;
25. What is a SELF JOIN?
A self join joins a table to itself.
It is useful for hierarchical data such as employees and managers.
SELECT
e.name AS employee,
m.name AS manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.employee_id;
Part 8: UNION vs UNION ALL
26. What is the difference between UNION and UNION ALL?
UNION
Combines result sets and removes duplicate rows.
SELECT city FROM customers
UNION
SELECT city FROM suppliers;
UNION ALL
Combines result sets without removing duplicates.
SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers;
If duplicates do not need to be removed, UNION ALL can avoid the extra duplicate-elimination work.
Part 9: NULL in SQL
27. What is NULL?
NULL represents an unknown, missing or unavailable value.
It is not the same as:
0- Empty string
FALSE
To test for NULL, use:
WHERE department_id IS NULL;
Not:
WHERE department_id = NULL;
28. What is COALESCE?
COALESCE() returns the first non-NULL expression.
Example:
SELECT
name,
COALESCE(phone, 'Not Available') AS phone
FROM customers;
Part 10: Subquery Interview Questions
29. What is a Subquery?
A subquery is a query inside another SQL query.
Example:
SELECT name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);
This returns employees whose salary is greater than the average salary.
30. What is a Correlated Subquery?
A correlated subquery references a value from the outer query.
Example:
SELECT e1.name, e1.salary, e1.department_id
FROM employees e1
WHERE e1.salary > (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department_id = e1.department_id
);
Here, the inner query depends on the current row from the outer query.
31. What is the difference between IN and EXISTS?
IN compares a value against a set of values.
SELECT *
FROM customers
WHERE customer_id IN (
SELECT customer_id
FROM orders
);
EXISTS checks whether the subquery returns at least one matching row.
SELECT *
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);
The best choice depends on the query, data distribution, optimizer and database engine.
Part 11: CTE Interview Questions
32. What is a CTE?
CTE stands for Common Table Expression.
It is defined using WITH.
Example:
WITH high_salary AS (
SELECT *
FROM employees
WHERE salary > 70000
)
SELECT *
FROM high_salary;
CTEs can make complex queries easier to read and maintain.
33. What is a Recursive CTE?
A recursive CTE refers to itself and is useful for hierarchical data.
Common examples include:
- Employee-manager hierarchies
- Folder structures
- Organizational trees
- Category hierarchies
Example:
WITH RECURSIVE employee_tree AS (
SELECT employee_id, name, manager_id
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.name, e.manager_id
FROM employees e
JOIN employee_tree t
ON e.manager_id = t.employee_id
)
SELECT *
FROM employee_tree;
The exact syntax varies by database.
Part 12: Window Function Interview Questions
Window functions are especially useful for ranking, running totals, comparisons with previous/next rows, and top-N-per-group problems.
34. What is a Window Function?
A window function calculates a value across related rows without collapsing the rows into one result per group.
Example:
SELECT
name,
department_id,
salary,
AVG(salary) OVER (
PARTITION BY department_id
) AS department_avg
FROM employees;
35. What is ROW_NUMBER()?
ROW_NUMBER() assigns a unique sequential number to rows.
SELECT
name,
salary,
ROW_NUMBER() OVER (
ORDER BY salary DESC
) AS row_num
FROM employees;
36. What is RANK()?
RANK() gives the same rank to tied values and leaves gaps after ties.
For salaries:
| Salary | RANK |
|---|---|
| 100000 | 1 |
| 100000 | 1 |
| 90000 | 3 |
37. What is DENSE_RANK()?
DENSE_RANK() also gives the same rank to ties, but does not leave gaps.
| Salary | DENSE_RANK |
|---|---|
| 100000 | 1 |
| 100000 | 1 |
| 90000 | 2 |
Knowing the difference between ROW_NUMBER(), RANK() and DENSE_RANK() is important for interview problems involving ties and ranking.
38. What is the difference between ROW_NUMBER, RANK and DENSE_RANK?
| Function | Handles ties | Skips rank |
|---|---|---|
| ROW_NUMBER | No shared rank | No |
| RANK | Same rank | Yes |
| DENSE_RANK | Same rank | No |
Part 13: Practical SQL Coding Interview Questions
Now let’s move from theory to the type of SQL problems you may be asked to solve during an interview.
39. How do you find the second-highest salary?
One approach is:
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (
SELECT MAX(salary)
FROM employees
);
This treats duplicate salary values as one salary level.
Another approach is:
SELECT salary
FROM (
SELECT
salary,
DENSE_RANK() OVER (
ORDER BY salary DESC
) AS rnk
FROM employees
) x
WHERE rnk = 2;
The window-function solution is particularly useful when the interviewer asks you to explain how ties should be handled.
40. How do you find the highest salary in each department?
SELECT
department_id,
MAX(salary) AS highest_salary
FROM employees
GROUP BY department_id;
If the interviewer also wants the employee’s name, a window function can be useful:
WITH ranked AS (
SELECT
name,
department_id,
salary,
RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS rnk
FROM employees
)
SELECT name, department_id, salary
FROM ranked
WHERE rnk = 1;
41. How do you find the top 3 employees in each department?
WITH ranked AS (
SELECT
employee_id,
name,
department_id,
salary,
ROW_NUMBER() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS rn
FROM employees
)
SELECT *
FROM ranked
WHERE rn <= 3;
If ties should all be included, consider RANK() or DENSE_RANK() instead.
42. How do you find duplicate records?
Suppose duplicate email addresses are stored in a users table.
SELECT
email,
COUNT(*) AS total
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
43. How do you find employees who do not have a department?
Using a LEFT JOIN:
SELECT e.*
FROM employees e
LEFT JOIN departments d
ON e.department_id = d.department_id
WHERE d.department_id IS NULL;
44. How do you find customers who have never placed an order?
SELECT c.*
FROM customers c
LEFT JOIN orders o
ON c.customer_id = o.customer_id
WHERE o.customer_id IS NULL;
An equivalent NOT EXISTS approach is:
SELECT c.*
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);
45. How do you calculate the total salary by department?
SELECT
department_id,
SUM(salary) AS total_salary
FROM employees
GROUP BY department_id;
46. How do you calculate average salary by department?
SELECT
department_id,
AVG(salary) AS average_salary
FROM employees
GROUP BY department_id;
47. How do you find employees earning more than the company average?
SELECT name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);
48. How do you find employees earning more than their department average?
SELECT
name,
department_id,
salary
FROM employees e
WHERE salary > (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department_id = e.department_id
);
Part 14: Running Total
49. How do you calculate a running total?
Suppose you have:
sale_date
amount
You can use:
SELECT
sale_date,
amount,
SUM(amount) OVER (
ORDER BY sale_date
) AS running_total
FROM sales;
This is a common example of why window functions are useful: the rows remain visible while the cumulative calculation is added.
Part 15: LAG and LEAD
50. What is LAG()?
LAG() retrieves a value from a previous row.
Example:
SELECT
sale_date,
amount,
LAG(amount) OVER (
ORDER BY sale_date
) AS previous_amount
FROM sales;
51. What is LEAD()?
LEAD() retrieves a value from a following row.
SELECT
sale_date,
amount,
LEAD(amount) OVER (
ORDER BY sale_date
) AS next_amount
FROM sales;
These functions are useful for:
- Month-over-month comparisons
- Previous transaction analysis
- Change detection
- Time-series analysis
Part 16: Database Normalization
52. What is Normalization?
Normalization is a database-design process used to organize data and reduce unnecessary duplication and update anomalies.
Common normal forms include:
- 1NF
- 2NF
- 3NF
- BCNF
53. What is First Normal Form (1NF)?
A table generally satisfies 1NF when each field contains atomic values rather than repeating groups or multiple values packed into a single field.
Bad example:
| Student | Subjects |
|---|---|
| Rahul | Maths, Science, English |
A normalized design could store subjects as separate rows.
54. What is Second Normal Form (2NF)?
2NF builds on 1NF and removes partial dependency on part of a composite key.
It is mainly relevant when a table has a composite primary key.
55. What is Third Normal Form (3NF)?
3NF builds on 2NF and aims to remove transitive dependencies.
In simple terms, non-key attributes should depend on the key rather than on another non-key attribute.
Part 17: SQL Index Interview Questions
56. What is an Index?
An index is a database structure that can help the database locate rows more efficiently.
Example:
CREATE INDEX idx_employee_email
ON employees(email);
Indexes can improve read performance for suitable queries, but they also consume storage and can add overhead to data modifications.
57. What are the disadvantages of indexes?
Indexes can:
- Consume additional storage
- Increase the cost of
INSERT - Increase the cost of
UPDATE - Increase the cost of
DELETE - Require maintenance
- Be ineffective for some query patterns
Therefore, adding an index to every column is not a good general strategy.
58. What is a composite index?
A composite index contains more than one column.
CREATE INDEX idx_employee_dept_salary
ON employees(department_id, salary);
Column order matters because the database can use the index differently depending on the query and database optimizer.
Part 18: Transactions and ACID
59. What is a Transaction?
A transaction is a logical unit of database work.
For example:
BEGIN;
UPDATE accounts
SET balance = balance - 1000
WHERE account_id = 1;
UPDATE accounts
SET balance = balance + 1000
WHERE account_id = 2;
COMMIT;
Both operations are intended to be part of the same transaction.
60. What is ACID?
ACID stands for:
Atomicity
A transaction is treated as a unit.
Consistency
The database should remain in a valid state according to its rules.
Isolation
Concurrent transactions should behave according to the database’s isolation guarantees.
Durability
Committed changes should persist despite subsequent failures, subject to the database system’s guarantees.
61. What is COMMIT?
COMMIT permanently saves a transaction.
COMMIT;
62. What is ROLLBACK?
ROLLBACK reverses changes that are still eligible to be rolled back within the current transaction.
ROLLBACK;
Part 19: Views
63. What is a View?
A view is a named query that can be queried like a table.
Example:
CREATE VIEW high_salary_employees AS
SELECT name, salary
FROM employees
WHERE salary > 70000;
Then:
SELECT *
FROM high_salary_employees;
Views can simplify access to commonly used queries and can also help expose only selected columns or rows.
Part 20: Stored Procedures
64. What is a Stored Procedure?
A stored procedure is a database-side program containing SQL statements and procedural logic supported by the database system.
The exact syntax differs between MySQL, SQL Server, PostgreSQL and Oracle.
Example syntax in a MySQL-style environment:
CREATE PROCEDURE GetEmployees()
BEGIN
SELECT *
FROM employees;
END;
Part 21: Triggers
65. What is a Trigger?
A trigger is database logic that automatically executes in response to specified events such as:
INSERTUPDATEDELETE
Example use cases include:
- Audit logging
- Maintaining derived data
- Enforcing certain business rules
Triggers should be designed carefully because they can make data changes less obvious to application developers.
Part 22: SQL Query Execution Order
66. What is the logical order of SQL query execution?
A simplified logical processing order is:
FROM
JOIN
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY
LIMIT / OFFSET
The exact implementation is optimizer-dependent, but understanding logical processing order helps explain questions such as why a window-function result generally cannot be filtered directly in the same query’s WHERE clause.
Part 23: Tricky SQL Interview Questions
67. Can WHERE be used with aggregate functions?
Generally, aggregate results such as COUNT() or AVG() are filtered using HAVING after grouping.
Example:
SELECT department_id, COUNT(*) AS total
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 10;
68. Can we use a column alias in WHERE?
In many SQL systems, a SELECT alias cannot be referenced in the same query block’s WHERE because of the logical processing order.
For example:
SELECT salary * 12 AS annual_salary
FROM employees
WHERE annual_salary > 600000;
may not work depending on the database.
A derived table or CTE can be used instead:
SELECT *
FROM (
SELECT
name,
salary * 12 AS annual_salary
FROM employees
) x
WHERE annual_salary > 600000;
69. What happens when NULL is compared using =?
Consider:
SELECT *
FROM employees
WHERE department_id = NULL;
This does not correctly test for NULL.
Use:
WHERE department_id IS NULL;
70. What is the NOT IN and NULL problem?
This is an important SQL edge case.
Consider:
WHERE employee_id NOT IN (
SELECT employee_id
FROM employees_backup
);
If the subquery contains NULL, three-valued SQL logic can produce unexpected results.
For many “does not exist” problems, NOT EXISTS is safer when NULL semantics are relevant:
WHERE NOT EXISTS (
SELECT 1
FROM employees_backup b
WHERE b.employee_id = e.employee_id
);
The important interview point is to understand NULL semantics, rather than blindly choosing one syntax.
Part 24: More Practical SQL Interview Problems
71. Find the third-highest salary
Using DENSE_RANK():
WITH ranked AS (
SELECT
salary,
DENSE_RANK() OVER (
ORDER BY salary DESC
) AS rnk
FROM employees
)
SELECT salary
FROM ranked
WHERE rnk = 3;
72. Find employees who have the same salary
SELECT salary, COUNT(*) AS employee_count
FROM employees
GROUP BY salary
HAVING COUNT(*) > 1;
73. Find the number of employees in each department
SELECT
department_id,
COUNT(*) AS employee_count
FROM employees
GROUP BY department_id;
74. Find departments having more than 5 employees
SELECT
department_id,
COUNT(*) AS employee_count
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 5;
75. Find the employee with the highest salary
SELECT *
FROM employees
WHERE salary = (
SELECT MAX(salary)
FROM employees
);
This returns all employees tied at the maximum salary.
76. Find the latest order for each customer
A window function is one way:
WITH ranked_orders AS (
SELECT
order_id,
customer_id,
order_date,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY order_date DESC
) AS rn
FROM orders
)
SELECT *
FROM ranked_orders
WHERE rn = 1;
77. Find monthly sales
A database-specific date function may be required.
Conceptually:
SELECT
YEAR(order_date) AS sales_year,
MONTH(order_date) AS sales_month,
SUM(amount) AS total_sales
FROM orders
GROUP BY
YEAR(order_date),
MONTH(order_date);
The exact date functions vary between MySQL, SQL Server, PostgreSQL and Oracle.
SQL Interview Questions for Freshers
If you are a fresher, focus first on these topics:
- What is SQL?
- DBMS vs RDBMS
- Primary key
- Foreign key
- Constraints
- DDL vs DML
- DELETE vs TRUNCATE vs DROP
- SELECT
- WHERE
- ORDER BY
- GROUP BY
- HAVING
- Aggregate functions
- INNER JOIN
- LEFT JOIN
- UNION vs UNION ALL
- NULL
- Subqueries
- Views
- Basic SQL queries
After mastering these, move to:
- CTEs
- Window functions
- Indexes
- Transactions
- Query optimization
SQL Interview Questions for Experienced Candidates
Experienced candidates should be prepared for SQL Interview Questions more than definitions.
Important topics include:
Query optimization
- Index selection
- Execution plans
- Join strategies
- Large-table queries
- Avoiding unnecessary scans
Advanced SQL
- CTEs
- Recursive CTEs
- Window functions
- Correlated subqueries
- Complex joins
- Conditional aggregation
Database design
- Normalization
- Denormalization
- Keys
- Relationships
- Constraints
Transactions
- ACID
- Isolation levels
- Locking
- Deadlocks
- Concurrency
Practical coding
- Top N per group
- Running totals
- Duplicate detection
- Missing records
- Gaps and sequences
- Previous/next row comparisons
15 SQL Queries You Should Practice Before an Interview
Before your interview, try writing these queries without looking at the solution:
Beginner
- Select all employees.
- Find employees earning more than ₹50,000.
- Sort employees by salary.
- Count employees.
- Find average salary.
Intermediate
- Find employees in each department.
- Find departments with more than 5 employees.
- Find the second-highest salary.
- Find duplicate emails.
- Find customers without orders.
Advanced
- Find the highest-paid employee in each department.
- Find the top 3 employees in each department.
- Calculate a running total.
- Find each employee’s previous salary record.
- Find the latest order for every customer.
These practical patterns cover many of the recurring SQL coding concepts discussed in current SQL Interview Questions -preparation material.
Common SQL Interview Mistakes / SQL Interview Questions Mistake
Avoid these mistakes during an SQL interview.
Mistake 1: Memorizing queries
Instead of memorizing:
SELECT ...
understand what the query is doing.
Mistake 2: Ignoring NULL
Always consider how NULL affects comparisons, joins and NOT IN.
Mistake 3: Confusing WHERE and HAVING
Remember:
WHERE → rows
HAVING → groups
Mistake 4: Ignoring ties
For ranking problems, ask whether duplicate values should receive the same rank.
Mistake 5: Using SELECT *
In production queries, selecting only the required columns can make queries clearer and may reduce unnecessary data retrieval.
Mistake 6: Adding indexes everywhere
Indexes can improve some reads but add storage and write overhead.
Mistake 7: Not explaining your logic
During a coding interview, explain:
- What you are trying to find.
- Which tables you need.
- How the tables are related.
- Why you selected a particular JOIN.
- How NULLs and duplicates are handled.
- Why your query produces the expected result.
How to Prepare for an SQL Interview Questions
Step 1: Learn SQL fundamentals
Start with:
SELECT
WHERE
ORDER BY
GROUP BY
HAVING
Step 2: Master JOINs
Practice:
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL OUTER JOIN
SELF JOIN
CROSS JOIN
Step 3: Practice aggregate functions
Learn:
COUNT()
SUM()
AVG()
MIN()
MAX()
Step 4: Learn subqueries and CTEs
Practice rewriting problems using:
- Subqueries
- CTEs
- JOINs
Step 5: Learn window functions
Focus on:
ROW_NUMBER()
RANK()
DENSE_RANK()
LAG()
LEAD()
SUM() OVER()
AVG() OVER()
Step 6: Solve practical problems
Do not only read SQL.
Write the queries yourself.
Try solving a problem first, then compare your answer with the solution.
Quick SQL Interview Questions Cheat Sheet
| Topic | Remember |
|---|---|
| WHERE | Filters rows |
| HAVING | Filters groups |
| GROUP BY | Groups rows |
| INNER JOIN | Matching rows |
| LEFT JOIN | All left + matches |
| UNION | Combines and removes duplicates |
| UNION ALL | Combines without duplicate removal |
| PRIMARY KEY | Unique row identifier |
| FOREIGN KEY | Table relationship |
| INDEX | Helps suitable lookups |
| CTE | Named temporary query expression |
| ROW_NUMBER | Unique sequence |
| RANK | Ties + gaps |
| DENSE_RANK | Ties without gaps |
| LAG | Previous row |
| LEAD | Next row |
| COMMIT | Save transaction |
| ROLLBACK | Undo eligible transaction changes |
| NULL | Missing/unknown value |
Frequently Asked Questions About SQL Interview Questions
What are the most common SQL interview questions?
Common areas include JOINs, GROUP BY, HAVING, aggregate functions, subqueries, window functions, indexes, transactions and practical query-writing.
Is SQL difficult for freshers?
The fundamentals can be learned progressively. The most important step is to practice writing queries rather than only reading SQL syntax.
Which SQL topics should a fresher learn first?
Start with:
- SELECT
- WHERE
- ORDER BY
- GROUP BY
- HAVING
- Aggregate functions
- JOINs
- Subqueries
Then move to CTEs and window functions.
What SQL queries are commonly asked in interviews?
Popular practical problems include:
- Second-highest salary
- Highest salary per department
- Duplicate records
- Employees without departments
- Customers without orders
- Top N records per group
- Running totals
- Latest record per customer
Should I learn MySQL or PostgreSQL for interviews?
Either can be a good choice. However, SQL syntax and features differ between database systems, so check which database your target role uses.
Are SQL JOINs important for interviews?
Yes. JOIN problems test whether you understand how information stored across multiple tables can be combined.
Are window functions important?
They are particularly useful for ranking, running calculations and comparing rows. They are also common in practical SQL interview questions.
Final SQL Interview Questions Preparation Checklist
Before attending your SQL interview, make sure you can confidently explain and write:
- SELECT
- WHERE
- ORDER BY
- GROUP BY
- HAVING
- Aggregate functions
- Primary key
- Foreign key
- Constraints
- INNER JOIN
- LEFT JOIN
- RIGHT JOIN
- FULL OUTER JOIN
- SELF JOIN
- UNION
- UNION ALL
- NULL
- Subqueries
- Correlated subqueries
- CTEs
- Window functions
- ROW_NUMBER
- RANK
- DENSE_RANK
- LAG
- LEAD
- Indexes
- Views
- Transactions
- ACID
- Normalization
- Query optimization
- Second-highest salary
- Top N per group
- Duplicate records
- Running totals
- Customers without orders
Conclusion
SQL interviews are not only about remembering SQL commands. Interviewers often want to see whether you can understand a data problem, choose the appropriate SQL technique, write a correct query, and explain your reasoning.
Start with SQL fundamentals, become comfortable with JOINs and aggregation, and then practice subqueries, CTEs and window functions.
Most importantly, write SQL queries yourself. Reading a solution is useful, but solving the problem without looking at the answer is what builds interview confidence.
Bookmark this SQL Interview Questions and Answers guide and use it as a revision checklist before your next technical interview.
More SQL, programming and interview preparation resources:
Visit our website .
For HTML Interview Questions click here
#SQL Interview Questions
