SQL Subqueries and CTEs Practice Questions
Harder questions need more than one step. Learn to break a problem into stages with WITH clauses, compare rows against a group result with correlated subqueries and reuse derived tables.
20 questions · 4 Easy · 12 Medium · 4 Hard · about 3.7 hours · MySQL & PostgreSQL
What you'll practise
- WITH clauses (CTEs)
- Scalar subqueries
- Correlated subqueries
- Derived tables
- Recursive CTEs
Learn the concepts first
Questions in this plan
Customers Who Never Order
Identify all customer records that have no matching entries in the Orders table.
Second Highest Delivery Fee
Return the second-highest distinct delivery fee, or NULL if there isn't one.
Monthly Listing Ratings
Average star rating for each listing in each month.
Largest Unique Number
Find the largest number that appears exactly once.
YouTube: Breakout Videos Dominating Channels
Find videos that account for at least 50% of their channel total views, calculating each video view percentage.
Second Highest Salary
Find the second highest distinct salary from the Employee table without duplicate values.
Find Duplicate Rows to Remove (Keep Lowest ID)
Formulate a query to eliminate duplicate email entries while preserving the record with smallest ID.
Nth Highest Salary
Write a dynamic MySQL stored procedure or subquery to retrieve the Nth distinct salary ranking.
Amazon: Repeat Purchase Rate
Calculate the percentage of all registered customers who have placed two or more orders, rounded to 2 decimal places.
Amazon: Above City Average Spend
Find customers whose total cumulative purchase spend exceeds the average customer spend in their respective city.
Amazon: First Order Details
Retrieve each customer's very first order, resolving date ties by selecting the lowest order_id.
Users Who Heard an Entire Playlist
Identify listeners who played every track of a given playlist at least once.
Most Watched Title per Genre
Find the title with the highest total watch time in each genre, keeping ties.
Org Chart Downstream Reports
List everyone who reports, directly or indirectly, to a given manager along with their depth.
Ordered Purchase Funnel
Measure a three-step conversion funnel where the steps must happen in order.
Camera Buyers Without Memory Cards
Find customers who bought a camera but never bought a memory card, and count their cameras.
Products Never Purchased Together
Cross-reference product catalog against order item baskets to detect inventory pair gaps.
Amazon: Prime Monthly Churn Rate
Calculate monthly Prime subscriber churn rates using calendar intervals and conditional status aggregations.
Amazon: Monthly Cohort Retention
Analyze customer retention cohorts across 1-month and 2-month subsequent repurchase cycles.
Longest Login Streaks
Find users who logged in on at least three consecutive days and report their best streak.