Follow on us YouTube:
https://youtube.com/@tarunkhandagare?si=rgzV8rYCcVECppXo
💡 Medium Level
1️⃣ Find the second highest salary in an employee table:
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
2️⃣ Fetch all employees whose names contain the letter “a” exactly twice:
SELECT *
FROM employees
WHERE name LIKE '%a%a%'
AND name NOT LIKE '%a%a%a%';
3️⃣ Retrieve only duplicate records from a table:
SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name
HAVING COUNT(*) > 1;
4️⃣ Calculate the running total of sales by date:
SELECT date, sales,
SUM(sales) OVER (ORDER BY date) AS running_total
FROM sales_table;
5️⃣ Find employees who earn more than the average salary in their department:
SELECT e.*
FROM employees e
JOIN (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
) d ON e.department_id = d.department_id
WHERE e.salary > d.avg_salary;
6️⃣ Find the most frequently occurring value in a column:
SELECT column_name, COUNT(*) AS frequency
FROM table_name
GROUP BY column_name
ORDER BY frequency DESC
LIMIT 1;
7️⃣ Fetch records where the date is within the last 7 days from today:
SELECT *
FROM table_name
WHERE date_column >= CURDATE() - INTERVAL 7 DAY;
8️⃣ Count how many employees share the same salary:
SELECT salary, COUNT(*) AS employee_count
FROM employees
GROUP BY salary
ORDER BY employee_count DESC;
9️⃣ Fetch the top 3 records for each group in a table:
SELECT *
FROM (
SELECT *,
RANK() OVER (PARTITION BY group_column ORDER BY some_column
DESC) AS rank
FROM table_name
) ranked_data
WHERE rank <= 3;
🔟 Retrieve products that were never sold (using LEFT JOIN):
SELECT p.*
FROM products p
LEFT JOIN sales s ON p.product_id = s.product_id
WHERE s.product_id IS NULL;
💡 Challenging Level
1️⃣ Retrieve customers who made their first purchase in the last 6 months:
SELECT customer_id
FROM orders
WHERE order_date = (
SELECT MIN(order_date)
FROM orders o
WHERE o.customer_id = orders.customer_id
)
AND order_date >= CURDATE() - INTERVAL 6 MONTH;
2️⃣ Pivot a table to convert rows into columns (Example: Sales by Month):
SELECT *
FROM (
SELECT customer_id, amount, MONTH(order_date) AS month
FROM sales
) s
PIVOT (
SUM(amount) FOR month IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
) p;
3️⃣ Calculate the percentage change in sales month-over-month:
SELECT year, month, sales,
(sales - LAG(sales) OVER (ORDER BY year, month)) / LAG(sales)
OVER (ORDER BY year, month) * 100 AS pct_change
FROM sales_table;
4️⃣ Find the median salary of employees:
SELECT salary
FROM (
SELECT salary,
ROW_NUMBER() OVER (ORDER BY salary) AS row_num,
COUNT(*) OVER () AS total_rows
FROM employees
) ranked
WHERE row_num = total_rows / 2 OR row_num = (total_rows / 2) + 1;
5️⃣ Fetch all users who logged in consecutively for 3 days or more:
SELECT user_id
FROM (
SELECT user_id, login_date,
LEAD(login_date, 1) OVER (PARTITION BY user_id ORDER BY
login_date) AS next_day,
LEAD(login_date, 2) OVER (PARTITION BY user_id ORDER BY
login_date) AS third_day
FROM logins
) consecutive_logins
WHERE next_day = login_date + INTERVAL 1 DAY
AND third_day = login_date + INTERVAL 2 DAY;
6️⃣ Delete duplicate rows while keeping one occurrence:
DELETE FROM employees
WHERE id NOT IN (
SELECT MIN(id)
FROM employees
GROUP BY name, salary, department_id
);
7️⃣ Calculate the ratio of sales between two categories:
SELECT
SUM(CASE WHEN category = 'Category_A' THEN sales ELSE 0 END) /
SUM(CASE WHEN category = 'Category_B' THEN sales ELSE 1 END) AS
sales_ratio
FROM sales_table;
8️⃣ Recursive query to generate a hierarchical structure:
WITH RECURSIVE hierarchy AS (
SELECT id, name, parent_id
FROM employees
WHERE parent_id IS NULL
UNION ALL
SELECT e.id, e.name, e.parent_id
FROM employees e
INNER JOIN hierarchy h ON e.parent_id = h.id
)
SELECT * FROM hierarchy;
9️⃣ Find gaps in sequential numbering within a table:
SELECT t1.id + 1 AS missing_number
FROM table_name t1
LEFT JOIN table_name t2 ON t1.id + 1 = t2.id
WHERE t2.id IS NULL;
🔟 Split a comma-separated string into individual rows using SQL:
SELECT value
FROM STRING_SPLIT('apple,banana,orange', ',');
💡 Advanced Problem-Solving
1️⃣ Rank products by sales in descending order for each region:
SELECT region, product_id, sales,
RANK() OVER (PARTITION BY region ORDER BY sales DESC) AS rank
FROM sales_table;
2️⃣ Fetch all employees whose salaries fall within the top 10% of their department:
SELECT *
FROM employees e
WHERE salary >= (
SELECT PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY salary)
FROM employees e2
WHERE e.department_id = e2.department_id
);
3️⃣ Identify orders placed during business hours (9 AM to 6 PM):
SELECT *
FROM orders
WHERE HOUR(order_time) BETWEEN 9 AND 18;
4️⃣ Count of users active on both weekdays and weekends:
SELECT user_id
FROM user_activity
WHERE DAYOFWEEK(activity_date) BETWEEN 2 AND 6
INTERSECT
SELECT user_id
FROM user_activity
WHERE DAYOFWEEK(activity_date) IN (1, 7);
5️⃣ Retrieve customers who made purchases across at least three different categories:
SELECT customer_id
FROM sales
GROUP BY customer_id
HAVING COUNT(DISTINCT category) >= 3;