Tricky and Logical SQL Questions
Set 1: Ranking & Analytics
Q1. Find the second highest salary without using LIMIT, TOP, or ROWNUM.
Q2. For each department, find the employee(s) with the highest salary.
Q3. List employees who earn more than the average salary of their department.
Q4. Get the Nth highest salary in a table.
Q5. Find the salary gap between each employee and the person ranked above them.
Set 2: Time Series & Date Logic
Q6. Find users who logged in every day for 7 consecutive days.
Q7. Identify login streaks and their lengths for each user.
Q8. Find employees whose birthdays are in the current month.
Q9. Count number of orders placed per week/month.
Q10. Detect gaps in order dates for a product.
Set 3: Self Joins & Recursive Queries
Q11. Find employees who earn more than their manager.
Q12. Find all managers who do not have any subordinates.
Q13. Find the entire management chain (CEO -> intern) using recursive CTE.
Q14. Print employee name and their managers manager name.
Q15. Using recursion, print numbers 1 to 100 (no table provided).
Set 4: Filtering, Grouping & Aggregation
Q16. Find departments where more than one employee has the same salary.
Q17. Find all customers who bought products from all categories.
Q18. Find customers who made multiple orders on the same day.
Q19. Find products that were never sold.
Q20. Find users who placed only one order and never returned.
Set 5: Window Functions (Advanced Analytics)
Q21. Get running total of sales per customer.
Q22. Rank orders per customer by amount.
Q23. Find the difference in salary between each employee and the next.
Q24. For each product, find the 3 most recent sale dates.
Q25. Detect duplicate rows using ROW_NUMBER().
Set 6: Nulls, Missing Data, Anti-Joins
Q26. Find customers who have never placed an order.
Q27. Find products that have never been restocked.
Q28. Find employees whose managers info is missing (null).
Q29. Replace null salaries with average salary of department.
Q30. Find all missing numbers in a sequence from 1 to N.
Set 7: Tricky Joins & Logic Puzzles
Q31. Given a table of users and friends (user_id, friend_id), find mutual friends.
Q32. Find top 3 selling products per store per month.
Q33. Find customer pairs who bought the same set of products.
Q34. Return employees who joined on the same date as someone in another department.
Q35. Find customers who placed an order in every quarter of the year.
Set 8: Real-World Use Cases
Q36. Marketing: Identify customers who responded to at least 3 out of 5 campaigns.
Q37. CRM: Find the average number of days between a customer's visits.
Q38. Finance: Identify duplicate transactions made on the same day for the same amount.
Q39. Delivery: Identify drivers who always deliver on time.
Q40. Healthcare: Find patients who were readmitted within 30 days.