Beginner SQL Problems (1-10)
Problem 1: Find top 5 customers by total spend
Schema:
customers: customer_id, name, email, city
orders: order_id, customer_id, amount, order_dateQuestion: Find the top 5 customers by total spend.
Solution:
SELECT
c.customer_id,
c.name,
SUM(o.amount) AS total_spend
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.name
ORDER BY total_spend DESC
LIMIT 5;Key concepts: JOIN, GROUP BY, aggregate (SUM), ORDER BY, LIMIT
Problem 2: Monthly revenue trend
Question: Calculate total revenue for each month in 2025.
Solution:
SELECT
DATE_TRUNC('month', order_date) AS month,
SUM(amount) AS monthly_revenue,
COUNT(*) AS order_count
FROM orders
WHERE EXTRACT(YEAR FROM order_date) = 2025
GROUP BY month
ORDER BY month;Key concepts: DATE_TRUNC, EXTRACT, GROUP BY date, WHERE filter
Problem 3: Find customers who never ordered
Question: List all customers who have never placed an order.
Solution:
SELECT c.customer_id, c.name, c.email
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE o.order_id IS NULL;
-- Alternative using NOT EXISTS
SELECT customer_id, name, email
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
);Key concepts: LEFT JOIN, IS NULL, NOT EXISTS, anti-join pattern
Intermediate SQL Problems (11-20)
Problem 11: Running total of sales
Question: Calculate cumulative revenue by order date.
Solution:
SELECT
order_date,
amount,
SUM(amount) OVER (ORDER BY order_date) AS running_total
FROM orders
ORDER BY order_date;Key concepts: Window functions, SUM() OVER(), ORDER BY in window
Problem 12: Rank products by category sales
Question: Rank products within each category by total sales.
Solution:
SELECT
category,
product_name,
SUM(sales) AS total_sales,
RANK() OVER (PARTITION BY category ORDER BY SUM(sales) DESC) AS rank_in_category
FROM products
GROUP BY category, product_name
ORDER BY category, rank_in_category;Key concepts: RANK(), PARTITION BY, window functions with GROUP BY
Problem 13: Find second highest salary
Question: Find the second highest salary in employees table.
Solution:
-- Using window function
SELECT DISTINCT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees
) ranked
WHERE rank = 2;
-- Using subquery
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);Key concepts: DENSE_RANK(), subquery, DISTINCT
⚠️ CheckpointQuiz error: Missing or invalid options array
Advanced SQL Problems (21-25)
Problem 21: Calculate 7-day moving average
Question: Calculate 7-day moving average of daily sales.
Solution:
SELECT
order_date,
daily_sales,
AVG(daily_sales) OVER (
ORDER BY order_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS moving_avg_7day
FROM (
SELECT order_date, SUM(amount) AS daily_sales
FROM orders
GROUP BY order_date
) daily_totals
ORDER BY order_date;Key concepts: Window frames, ROWS BETWEEN, moving average
Problem 22: Month-over-month growth rate
Question: Calculate MoM revenue growth percentage.
Solution:
WITH monthly_revenue AS (
SELECT
DATE_TRUNC('month', order_date) AS month,
SUM(amount) AS revenue
FROM orders
GROUP BY month
)
SELECT
month,
revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_month_revenue,
((revenue - LAG(revenue) OVER (ORDER BY month)) /
LAG(revenue) OVER (ORDER BY month) * 100) AS growth_pct
FROM monthly_revenue
ORDER BY month;Key concepts: CTEs, LAG(), percentage calculation, window functions
Problem 23: Find gaps in sequence
Question: Find missing order IDs in sequence (1,2,3,5,7 → missing: 4,6).
Solution:
WITH RECURSIVE all_ids AS (
SELECT MIN(order_id) AS id FROM orders
UNION ALL
SELECT id + 1 FROM all_ids
WHERE id < (SELECT MAX(order_id) FROM orders)
)
SELECT a.id AS missing_order_id
FROM all_ids a
LEFT JOIN orders o ON a.id = o.order_id
WHERE o.order_id IS NULL
ORDER BY a.id;Key concepts: Recursive CTE, sequence generation, anti-join
Problem 24: Cohort retention analysis
Question: Calculate monthly retention cohorts.
Solution:
WITH first_purchase AS (
SELECT
customer_id,
DATE_TRUNC('month', MIN(order_date)) AS cohort_month
FROM orders
GROUP BY customer_id
),
purchase_months AS (
SELECT DISTINCT
customer_id,
DATE_TRUNC('month', order_date) AS purchase_month
FROM orders
)
SELECT
fp.cohort_month,
pm.purchase_month,
COUNT(DISTINCT pm.customer_id) AS active_customers,
ROUND(
COUNT(DISTINCT pm.customer_id) * 100.0 /
(SELECT COUNT(*) FROM first_purchase WHERE cohort_month = fp.cohort_month),
1
) AS retention_pct
FROM first_purchase fp
JOIN purchase_months pm ON fp.customer_id = pm.customer_id
GROUP BY fp.cohort_month, pm.purchase_month
ORDER BY fp.cohort_month, pm.purchase_month;Key concepts: Multiple CTEs, cohort analysis, retention calculation
Problem 25: Find duplicate transactions
Question: Find customers who made duplicate purchases (same product, same day).
Solution:
SELECT
customer_id,
product_id,
order_date,
COUNT(*) AS duplicate_count
FROM orders
GROUP BY customer_id, product_id, order_date
HAVING COUNT(*) > 1
ORDER BY duplicate_count DESC;Key concepts: GROUP BY multiple columns, HAVING for group filter
SQL Interview Tips
Before the Interview:
- Practice on platforms: LeetCode SQL, HackerRank, StrataScratch
- Know your window functions: RANK, LAG, LEAD, ROW_NUMBER, running totals
- Master JOINs: INNER, LEFT, FULL OUTER, self-join, anti-join patterns
- Understand CTEs: When to use WITH, recursive CTEs
- Date manipulation: DATE_TRUNC, EXTRACT, date arithmetic
During the Interview:
✅ Clarify requirements: "Should we include canceled orders?" "What if there are ties?" ✅ Start with simple solution: Get working query first, optimize later ✅ Explain your thinking: "I'm using LEFT JOIN to find customers without orders" ✅ Test with sample data: Walk through logic with example rows ✅ Consider edge cases: NULL values, empty tables, ties in ranking
Common Patterns:
| Pattern | When to Use | Example | |---------|-------------|---------| | LEFT JOIN + IS NULL | Find records without match | Customers who never ordered | | WINDOW FUNCTION | Running totals, rankings, previous values | Cumulative sales, top 3 per category | | CTE | Break complex query into steps | Multi-step calculations | | HAVING | Filter grouped results | Categories with >100 products | | CASE WHEN | Conditional logic | Categorize (if revenue >1M then 'High') |
⚠️ FinalQuiz error: Missing or invalid questions array
⚠️ SummarySection error: Missing or invalid items array
Received: {"hasItems":false,"isArray":false}