IMPORTANT SQL INTERVIEW
QUESTIONS
Order of execution in an SQL query:-
1. FROM /Join
2. WHERE
3. GROUP BY
4. HAVING
5. SELECT
6. DISTINCT
7. ORDER BY
8. LIMIT / OFFSET
Question 1: Write a SQL query to calculate the cumulative sum of sales for each
employee. The query should return the EmployeeID, SalesDate, and
CumulativeSales columns, with the final output ordered by EmployeeID.
Solution -
SELECT
EmployeeID,
SalesDate,
SUM(SalesAmount) OVER (PARTITION BY EmployeeID
ORDER BY SalesDate) AS CumulativeSales
FROM Employee
ORDER BY
EmployeeID;
Solution Explanation by Execution steps:-
Step 1 -> FROM - Employee Table
Step 2 -> PARTITION BY EmployeeID and ORDER BY SalesDate
● Partition for EmployeeID = 101 (Ordered by SalesDate):
● Partition for EmployeeID = 102 (Ordered by SalesDate):
● Partition for EmployeeID = 103 (Ordered by SalesDate):
Step 3: Cumulative Sum Calculation (SUM() OVER) As New
Column (CumulativeSales)-
● Partition for EmployeeID = 101:
● Partition for EmployeeID = 102:
● Partition for EmployeeID = 103:
Final Output Ordered by EmployeeID and By Only Selecting Required 3
columns (EmployeeID, SalesDate, CumulativeSales):-
Question 2: Write a SQL query to find employees who have a salary greater than
their manager's salary from the Employee table.
Solution -
SELECT
e1.EmployeeID AS e1_EmployeeID,
e1.EmployeeName AS e1_EmployeeName,
e1.Salary AS e1_Salary
FROM
Employee e1
JOIN
Employee e2
ON
e1.ManagerID = e2.EmployeeID
WHERE
e1.Salary > e2.Salary;
Solution Explanation by Execution steps:-
Step 1 -> FROM - Employee Table
Step 2 -> JOIN Clause - e1.ManagerID = e2.EmployeeID
The JOIN clause links the Employee table (as e1) with itself (as e2) based on
the ManagerID. This means for each employee in e1, we find the corresponding
manager in e2.
Step 3: WHERE Clause - e1.Salary > e2.Salary
The WHERE clause filters the rows where the employee's salary (e1.Salary) is
greater than their manager's salary (e2.Salary).
Step 4: SELECT Clause - SELECT e1.EmployeeID AS e1_EmployeeID,
e1.EmployeeName AS e1_EmployeeName, e1.Salary AS e1_Salary
The SELECT clause retrieves the EmployeeID, EmployeeName, and Salary
columns for employees who meet the condition.
Final Output:-
Question 3: Given a table Employees, write a query to find the third highest
salary.
Solution -
WITH SalaryRank AS (
SELECT Salary,
DENSE_RANK() OVER (ORDER BY Salary DESC) AS SalaryRank
FROM Employees
)
SELECT Salary
FROM SalaryRank
WHERE SalaryRank = 3;
Question 4: Given a table Purchases, write a query to find employees who
bought a product for at least 3 consecutive days.
Solution -
SELECT DISTINCT p1.EmployeeID
FROM Purchases p1
JOIN Purchases p2 ON p1.EmployeeID = p2.EmployeeID
AND DATE_ADD(p1.PurchaseDate, INTERVAL 1 DAY) = p2.PurchaseDate
JOIN Purchases p3 ON p2.EmployeeID = p3.EmployeeID
AND DATE_ADD(p2.PurchaseDate, INTERVAL 1 DAY) = p3.PurchaseDate;