Preparing for an SQL interview involves understanding various types of queries, ranging from basic SELECT statements to more complex operations involving joins, subqueries, aggregations, and window functions. Below are some of the most commonly asked SQL interview questions along with their answers and explanations to help you prepare effectively.
1. Retrieve All Records from a Table
Question:
Write a SQL query to retrieve all records from a table named Employees.
Answer:
sql
SELECT * FROM Employees;
Explanation:
The SELECT * statement retrieves all columns from the Employees table. It's a fundamental query used to fetch complete data from a table.
2. Find the Second Highest Salary
Question:
Given a table Employees with a column Salary, write a SQL query to find the second highest salary.
Answer:
sql
SELECT MAX(Salary) AS SecondHighestSalary
FROM Employees
WHERE Salary < (SELECT MAX(Salary) FROM Employees);
Explanation:
The subquery SELECT MAX(Salary) FROM Employees finds the highest salary.
The main query then selects the maximum salary from the Employees table where the salary is less than the highest salary, effectively retrieving the second highest salary.
3. Retrieve Employees Without a Manager
Question:
Given a table Employees with columns EmployeeID, Name, and ManagerID, write a SQL query to find all employees who do not have a manager.
Answer:
sql
SELECT Name
FROM Employees
WHERE ManagerID IS NULL;
Explanation:
Employees without a manager will have NULL in the ManagerID column. The IS NULL condition filters out these employees.
4. Join Two Tables
Question:
You have two tables, Employees and Departments. The Employees table has EmployeeID, Name, DepartmentID, and the Departments table has DepartmentID, DepartmentName. Write a SQL query to retrieve each employee's name along with their department name.
Answer:
sql
SELECT E.Name, D.DepartmentName
FROM Employees E
JOIN Departments D ON E.DepartmentID = D.DepartmentID;
Explanation:
The JOIN operation combines rows from Employees (E) and Departments (D) based on the matching DepartmentID. This retrieves each employee's name and their corresponding department name.
5. Aggregate Functions: Calculate Total Sales
Question:
Given a table Sales with a column Amount, write a SQL query to calculate the total sales.
Answer:
sql
SELECT SUM(Amount) AS TotalSales
FROM Sales;
Explanation:
The SUM() aggregate function adds up all the values in the Amount column, providing the total sales.
6. Group By and Having: Employees in Each Department
Question:
Using the Employees table, write a SQL query to find the number of employees in each department, but only include departments with more than 5 employees.
Answer:
sql
SELECT DepartmentID, COUNT(*) AS NumEmployees
FROM Employees
GROUP BY DepartmentID
HAVING COUNT(*) > 5;
Explanation:
GROUP BY DepartmentID groups the records by department.
COUNT(*) counts the number of employees in each group.
HAVING COUNT(*) > 5 filters the groups to include only those departments with more than five employees.
7. Subquery: Employees Earning More Than Average Salary
Question:
Write a SQL query to find all employees whose salaries are higher than the average salary.
Answer:
sql
SELECT Name, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
Explanation:
The subquery SELECT AVG(Salary) FROM Employees calculates the average salary. The main query selects employees whose Salary is greater than this average.
8. Using Window Functions: Ranking Employees by Salary
Question:
Write a SQL query to assign a rank to each employee based on their salary, with the highest salary getting rank 1.
Answer:
sql
SELECT
Name,
Salary,
RANK() OVER (ORDER BY Salary DESC) AS SalaryRank
FROM Employees;
Explanation:
The RANK() window function assigns a rank to each employee based on the Salary in descending order. Employees with the same salary receive the same rank.
9. Update Records: Increase Salary by 10% for a Specific Department
Question:
Write a SQL query to increase the salary of all employees in the 'Sales' department by 10%.
Answer:
sql
UPDATE Employees
SET Salary = Salary * 1.10
WHERE DepartmentID = (SELECT DepartmentID FROM Departments WHERE DepartmentName = 'Sales');
Explanation:
The subquery finds the DepartmentID for 'Sales'.
The UPDATE statement increases the Salary by 10% (Salary * 1.10) for all employees belonging to that DepartmentID.
10. Delete Duplicate Records
Question:
Given a table Employees that may contain duplicate records based on Name and DepartmentID, write a SQL query to delete the duplicate records, keeping only one instance.
Answer:
sql
WITH CTE AS (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY Name, DepartmentID ORDER BY EmployeeID) AS rn
FROM Employees
)
DELETE FROM CTE
WHERE rn > 1;
Explanation:
The Common Table Expression (CTE) assigns a row number (rn) to each record partitioned by Name and DepartmentID.
The DELETE statement removes all records where rn > 1, effectively keeping only the first occurrence of each duplicate.
Note: Some SQL databases might require different syntax for deleting from a CTE. Alternatively, you can use a DELETE with a subquery or temporary table based on your specific SQL dialect.
11. Find Missing Dates in a Sequence
Question:
Given a table Calendar with a column Date, write a SQL query to find missing dates in the sequence between the minimum and maximum dates.
Answer:
sql
WITH DateRange AS (
SELECT MIN(Date) AS StartDate, MAX(Date) AS EndDate
FROM Calendar
),
Numbers AS (
SELECT TOP (DATEDIFF(DAY, (SELECT StartDate FROM DateRange), (SELECT EndDate FROM DateRange)) + 1)
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 AS n
FROM sys.objects
),
AllDates AS (
SELECT DATEADD(DAY, n, (SELECT StartDate FROM DateRange)) AS Date
FROM Numbers
)
SELECT a.Date
FROM AllDates a
LEFT JOIN Calendar c ON a.Date = c.Date
WHERE c.Date IS NULL
ORDER BY a.Date;
Explanation:
This query generates all dates within the range and then finds which dates are missing by performing a LEFT JOIN between the generated dates and the existing dates in the Calendar table. Missing dates will have NULL in the Calendar table.
Note: The method to generate numbers (using sys.objects) may vary based on the SQL database being used.
12. Pivot Table: Sales per Year
Question:
Given a table Sales with columns Year, Quarter, and Amount, write a SQL query to pivot the data to show total sales for each quarter per year.
Answer:
sql
SELECT
Year,
SUM(CASE WHEN Quarter = 'Q1' THEN Amount ELSE 0 END) AS Q1,
SUM(CASE WHEN Quarter = 'Q2' THEN Amount ELSE 0 END) AS Q2,
SUM(CASE WHEN Quarter = 'Q3' THEN Amount ELSE 0 END) AS Q3,
SUM(CASE WHEN Quarter = 'Q4' THEN Amount ELSE 0 END) AS Q4
FROM Sales
GROUP BY Year
ORDER BY Year;
Explanation:
This query uses CASE statements within aggregate functions to sum the Amount for each quarter, effectively pivoting the data to display quarters as columns and years as rows.
13. Common Table Expressions (CTE): Hierarchical Data
Question:
Given a table Employees with EmployeeID, Name, and ManagerID, write a SQL query using CTE to list all employees along with their managers up to the top level.
Answer:
sql
WITH EmployeeHierarchy AS (
SELECT EmployeeID, Name, ManagerID, 1 AS Level
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmployeeID, e.Name, e.ManagerID, eh.Level + 1
FROM Employees e
INNER JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID
)
SELECT *
FROM EmployeeHierarchy
ORDER BY Level, ManagerID, EmployeeID;
Explanation:
The CTE EmployeeHierarchy starts with top-level employees who have no managers (ManagerID IS NULL).
It then recursively joins the Employees table to find subordinates, incrementing the Level each time to indicate hierarchy depth.
The final SELECT retrieves all employees with their hierarchical level.
14. Indexing: Improve Query Performance
Question:
Explain how indexing can improve query performance and provide an example of creating an index on the Employees table for the DepartmentID column.
Answer:
Explanation:
Indexing improves query performance by allowing the database to locate and access the data more efficiently without scanning the entire table. An index on a column like DepartmentID can speed up queries that filter or join based on this column.
Example:
sql
CREATE INDEX idx_department_id ON Employees(DepartmentID);
Explanation:
This statement creates an index named idx_department_id on the DepartmentID column of the Employees table. Now, queries filtering by DepartmentID can utilize this index for faster access.
15. Transactions: Ensuring Data Integrity
Question:
Explain what a transaction is in SQL and provide an example of using transactions to transfer funds between two bank accounts.
Answer:
Explanation:
A transaction is a sequence of one or more SQL operations treated as a single unit of work. Transactions ensure data integrity by adhering to the ACID properties (Atomicity, Consistency, Isolation, Durability). If any part of the transaction fails, the entire transaction is rolled back, leaving the database unchanged.
Example:
sql
BEGIN TRANSACTION;
UPDATE Accounts
SET Balance = Balance - 100
WHERE AccountID = 1;
UPDATE Accounts
SET Balance = Balance + 100
WHERE AccountID = 2;
IF @@ERROR <> 0
BEGIN
ROLLBACK TRANSACTION;
PRINT 'Transaction Failed';
END
ELSE
BEGIN
COMMIT TRANSACTION;
PRINT 'Transaction Successful';
END
Explanation:
The BEGIN TRANSACTION starts the transaction.
The first UPDATE deducts $100 from Account 1.
The second UPDATE adds $100 to Account 2.
If any error occurs (@@ERROR <> 0), the transaction is rolled back, undoing both updates.
If no errors occur, the transaction is committed, making both updates permanent.
Note: Error handling syntax may vary based on the SQL dialect (e.g., T-SQL for SQL Server). Modern SQL may use TRY...CATCH blocks for better error handling.
16. Temporary Tables vs. CTEs
Question:
What is the difference between using temporary tables and Common Table Expressions (CTEs) in SQL?
Answer:
Explanation:
Temporary Tables:
Definition: Temporary tables are physical tables stored in the tempdb database. They can be global (##TempTable) or local (#TempTable).
Usage: Useful for storing intermediate results that need to be accessed multiple times, especially in complex procedures.
Lifetime: Persist for the duration of the database session (local) or until the server is restarted (global).
Advantages: Support indexing, can be referenced multiple times, useful for breaking down complex operations.
Common Table Expressions (CTEs):
Definition: CTEs are temporary result sets defined within the execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement.
Usage: Ideal for simplifying complex queries, such as those involving recursion or multiple layers of subqueries.
Lifetime: Exist only for the duration of the single query they are part of.
Advantages: Enhance query readability, support recursion, no need to manage physical storage.
Example of Temporary Table:
sql
CREATE TABLE #TempEmployees (EmployeeID INT, Name VARCHAR(50));
INSERT INTO #TempEmployees
SELECT EmployeeID, Name FROM Employees WHERE DepartmentID = 1;
SELECT * FROM #TempEmployees;
Example of CTE:
sql
WITH SalesCTE AS (
SELECT EmployeeID, SUM(Amount) AS TotalSales
FROM Sales
GROUP BY EmployeeID
)
SELECT E.Name, S.TotalSales
FROM Employees E
JOIN SalesCTE S ON E.EmployeeID = S.EmployeeID;
17. Handling NULL Values
Question:
Explain how SQL handles NULL values and how to write a query that selects records where a column is not NULL.
Answer:
Explanation:
NULL in SQL: Represents the absence of a value or an unknown value. It is not equivalent to an empty string or zero.
Handling NULL: When performing comparisons or aggregations, NULL values behave differently. For example, NULL in any arithmetic operation results in NULL.
Checking for NULL: Use IS NULL or IS NOT NULL instead of = NULL or <> NULL.
Example Query (Select records where ManagerID is not NULL):
sql
SELECT Name, ManagerID
FROM Employees
WHERE ManagerID IS NOT NULL;
Explanation:
This query selects all employees who have a manager by filtering out records where ManagerID is NULL.
18. String Functions: Concatenate First and Last Names
Question:
Given a table Employees with FirstName and LastName, write a SQL query to display the full name of each employee.
Answer:
sql
SELECT FirstName + ' ' + LastName AS FullName
FROM Employees;
Explanation:
This query concatenates the FirstName and LastName columns with a space in between to form the FullName. Note that string concatenation operators may vary between SQL dialects (e.g., || in Oracle).
Alternative (Using CONCAT function for SQL Server and others):
sql
SELECT CONCAT(FirstName, ' ', LastName) AS FullName
FROM Employees;
19. Date Functions: Calculate Age
Question:
Given a table Employees with a column BirthDate, write a SQL query to calculate each employee's age.
Answer (SQL Server Example):
sql
SELECT Name,
DATEDIFF(YEAR, BirthDate, GETDATE()) -
CASE
WHEN MONTH(BirthDate) > MONTH(GETDATE())
OR (MONTH(BirthDate) = MONTH(GETDATE()) AND DAY(BirthDate) > DAY(GETDATE()))
THEN 1
ELSE 0
END AS Age
FROM Employees;
Explanation:
DATEDIFF(YEAR, BirthDate, GETDATE()) calculates the difference in years between BirthDate and the current date.
The CASE statement adjusts the age if the employee hasn't had their birthday yet in the current year.
Note: Date functions can vary between SQL dialects. For example, in MySQL, you might use TIMESTAMPDIFF.
20. Advanced: Recursive CTE for Hierarchical Data
Question:
Using a recursive CTE, write a SQL query to list all subordinates (direct and indirect) of a manager with EmployeeID = 1.
Answer:
sql
WITH RecursiveCTE AS (
-- Anchor member: direct subordinates of EmployeeID = 1
SELECT EmployeeID, Name, ManagerID, 1 AS Level
FROM Employees
WHERE ManagerID = 1
UNION ALL
-- Recursive member: subordinates of the current level
SELECT e.EmployeeID, e.Name, e.ManagerID, r.Level + 1
FROM Employees e
INNER JOIN RecursiveCTE r ON e.ManagerID = r.EmployeeID
)
SELECT *
FROM RecursiveCTE
ORDER BY Level, EmployeeID;
Explanation:
Anchor Member: Selects employees who directly report to the manager with EmployeeID = 1.
Recursive Member: Joins the Employees table with the CTE to find employees reporting to the current level's employees.
The Level column indicates the depth in the hierarchy.
The final SELECT retrieves all subordinates, ordered by their hierarchical level.
Tips for SQL Interviews:
Understand the Basics: Ensure you have a strong grasp of basic SQL operations like SELECT, INSERT, UPDATE, DELETE, JOIN, GROUP BY, and ORDER BY.
Practice Writing Queries: Regularly practice writing queries to solve different problems. Websites like LeetCode, HackerRank, and SQLZoo offer interactive SQL problems.
Know Your SQL Dialect: Different databases (e.g., MySQL, SQL Server, Oracle, PostgreSQL) have variations in syntax and functions. Be familiar with the one relevant to the job you're applying for.
Optimize Queries: Understand how indexes work and how to write efficient queries that use indexes properly. Be prepared to discuss query optimization techniques.
Understand Transactions and ACID Properties: Be ready to explain transactions, their properties, and how they ensure data integrity.
Study Advanced Topics: Familiarize yourself with window functions, CTEs, recursive queries, and subqueries, as these are commonly explored in interviews.
Problem-Solving Approach: In interviews, clearly explain your thought process when approaching a problem. Even if you don't reach the correct answer immediately, showing logical reasoning can earn partial credit.
Practice Explaining: Verbally explaining your queries and the reasoning behind them can help solidify your understanding and prepare you for real interview scenarios.
By reviewing these common SQL interview questions and their solutions, you can enhance your understanding and improve your confidence for your upcoming interviews. Remember to practice writing and explaining SQL queries, as hands-on experience is invaluable when tackling real-world SQL problems.