SQL challenges
85 problems on real databases, from your first WHERE to window functions and transactions.
34 are free. Everything runs in your browser.
- Easy
Find the Runner-Up Salary
Your company wants to identify the second-highest paid employee to understand compensation distribution.
AggregationSubqueries employees - Easy
Large Department Report
The HR team needs a report showing which departments have grown beyond a certain size threshold.
JOINsAggregation employees - Easy
New Hire Onboarding List
The onboarding team wants to track employees who joined within the last quarter (90 days) for a welcome event.
SELECT & filtering employees - Easy
Find Duplicate Email Addresses
The security team discovered that some users accidentally created multiple accounts with the same email during a migration.
Aggregation ecommerce - Easy
Merge Active and Inactive Users
The product team needs a combined list of both active and recently deactivated users for an engagement campaign.
SELECT & filtering ecommerce - Easy
Course Completion Percentage
The education platform wants to calculate what percentage of enrolled students actually completed each course.
SELECT & filtering school - Easy
Employees Without Managers
HR discovered some employee records have NULL in the manager_id field, indicating either top executives or data quality issues.
SELECT & filtering employees - Easy
Search Products by Name Pattern
The search team is testing a feature to find all products with 'Pro' in their names.
SELECT & filtering ecommerce - Easy
Calculate Account Age in Days
The retention team wants to segment users by how long they've been subscribers.
SELECT & filtering ecommerce - Easy
Average Order Value by Customer
The payments team needs to calculate average transaction size per customer to identify high-value customers.
Aggregation ecommerce - Easy
Convert Track Duration to Minutes
The music app needs to display track lengths in a user-friendly format.
SELECT & filtering music - Easy
Course Enrollment Numbers
The education team wants to see which courses are most popular.
JOINsAggregation school - Easy
Six-Figure Earners
Recruiting wants to identify employees earning above $100,000 for a compensation benchmark study.
SELECT & filtering employees - Easy
Group Albums by Decade
The music team wants to analyze catalog distribution across decades.
Aggregation music - Easy
Students Exceeding Average GPA
Academic advisors want to recognize students performing above the school average.
AggregationSubqueries school - Easy
Customer Lifetime Value
The finance team needs to calculate total revenue generated by each customer.
JOINsAggregation ecommerce - Easy
Email Domain Analysis
Marketing wants to know which email providers customers use most.
Aggregation ecommerce - Easy
Order Status Distribution
Operations needs a breakdown of order statuses to identify bottlenecks.
Aggregation ecommerce - Easy
Hiring Date Range
HR wants to know the span of hiring dates to understand company growth timeline.
Aggregation employees - Easy
Mid-Range Product Filter
Sales wants to promote mid-tier products priced between $50 and $200.
SELECT & filtering ecommerce - Easy
Handle Missing Data with COALESCE
The org chart page breaks on employees with no manager: their manager_id is NULL. The frontend team needs a safe fallback.
SELECT & filtering employees - Easy
Classify Employees by Salary Tier
Compensation wants to categorize every employee into salary bands for a benefits report.
SELECT & filtering employees - Easy
List Unique Product Categories
The catalog team needs a clean list of all product categories without duplicates.
Aggregation ecommerce - Easy
Each Artist's Longest Song
The playlist curation team wants to find each artist's longest track for a "Deep Cuts" playlist.
JOINsSubqueries music - Easy
Conditional Counting with SUM+CASE
Management wants a single-row summary showing employee counts by salary range without multiple queries.
Aggregation employees - Easy
Stock a New Product
A merchant just added a mechanical keyboard to their store, and it needs to go into the catalog.
Writes & indexes ecommerce - Easy
Engineering Gets a Raise
The comp committee approved a flat $5,000 raise for everyone in Engineering (department_id 1).
Writes & indexes employees - Easy
Relabel the Genre
The catalog team decided 'Hard Rock' should be merged into the 'Metal' genre for playlist curation.
Writes & indexes music - Easy
Speed Up Customer Lookups
The dashboard's most frequent query is "orders for customer X", and it's doing a full table scan every time.
Writes & indexes ecommerce - Medium
Identify Top 3 Earners per Department
Management wants to recognize the top 3 highest-paid employees in each department for a performance bonus program.
JOINsSubqueries employees - Medium
Find Customer's Third Purchase
The analytics team wants to understand customer behavior by analyzing their third purchase specifically.
SubqueriesWindow functions ecommerce - Medium
Daily Active User Streaks
The growth team wants to reward users who have maintained consecutive days of activity.
AggregationSubqueries ecommerce - Medium
Daily Running Total of Sales
Finance needs a report showing cumulative daily revenue to track toward quarterly goals.
AggregationWindow functions ecommerce - Medium
Product Rankings with Tie Handling
The marketplace team needs to rank products by rating, showing both RANK and DENSE_RANK to understand tie handling.
Window functions ecommerce - Medium
Compare Sales to Previous Day
Trading analytics wants to show daily stock price changes by comparing each day to the previous day.
SubqueriesWindow functions ecommerce - Medium
Detect Missing Order IDs
The operations team suspects some orders were lost in a system migration. They need to find gaps in the order ID sequence.
JOINsAggregation ecommerce - Medium
Pivot Sales by Month
Sales leadership wants a report showing each product's revenue pivoted by month (columns for Jan, Feb, Mar).
Aggregation ecommerce - Medium
Employee Reporting Structure
HR needs a report showing each employee alongside their direct manager's information for org chart visualization.
JOINs employees - Medium
Calculate 90th Percentile Salary
Compensation analysts need to find the 90th percentile salary to benchmark against market rates.
AggregationSubqueries employees - Medium
Customer Order Bookends
Analytics wants to compare each customer's first and last purchase to understand behavior evolution.
Aggregation ecommerce - Medium
Inactive Customers Report
Marketing wants to identify customers who registered but never made a purchase for a win-back campaign.
JOINs ecommerce - Medium
7-Day Moving Average of Sales
Finance wants to smooth out daily sales volatility by calculating a 7-day rolling average.
AggregationSubqueries ecommerce - Medium
Frequently Bought Together
The recommendation engine needs to find product pairs frequently purchased in the same order.
JOINsAggregation ecommerce - Medium
Cumulative Student Enrollment Growth
The growth team wants to visualize total cumulative enrollments over time.
AggregationSubqueries school - Medium
Find Employees Hired on Same Day
HR wants to identify orientation cohorts - groups of employees hired on the same date.
Aggregation employees - Medium
Select Every Other Row
A data engineer needs to sample every other record for an A/B testing control group.
JOINsSubqueries ecommerce - Medium
Above-Average Track Length per Album
The music team wants to identify unusually long tracks on each album.
JOINsAggregation music - Medium
Best Seller in Each Category
Merchandising wants to feature the top-selling product from each category on the homepage.
JOINsAggregation ecommerce - Medium
Find Customers With Recent Orders
The retention team wants to target customers who placed at least one order in 2024.
Subqueries ecommerce - Medium
Compare Employee Salary to Department Average
Each employee's review includes how their salary compares to their department's average.
JOINsAggregation employees - Medium
Complete Order Detail Report
Finance needs a complete order breakdown showing customer, product, and pricing details all in one report.
JOINs ecommerce - Medium
Most Prolific Artists
The editorial team wants to feature artists ranked by their catalog size.
JOINsAggregation music - Medium
Student GPA Ranking with Ties
Academic honors requires ranking students by GPA, handling ties properly so no ranks are skipped.
Window functions school - Medium
Academic Fresh Start
The registrar's new "fresh start" policy erases all C-range grades (C+, C, and C-) so students can retake those courses.
Writes & indexes school - Medium
Idempotent Customer Import
A CSV import can contain customers you already have. The import must never crash on duplicates - existing rows win.
Writes & indexes ecommerce - Medium
Tiered Annual Bonus
Annual bonuses are tiered by role: VPs get $10,000, anyone with 'Manager' in their title gets $5,000, and everyone else gets $2,000.
Writes & indexes employees - Medium
The Two-Column Index
The player constantly asks "tracks on album X, ordered by duration". One composite index can serve both the filter and the sort.
Writes & indexes music - Medium
One Account per Email
Support keeps merging duplicate student accounts. The fix: make the database itself refuse duplicate emails.
Writes & indexes school - Medium
Archive the Churned User
User 3 (Charlie) hasn't logged in for a year. Policy says churned accounts move to the archive table.
Writes & indexes ecommerce - Medium
The Manager Moved On
Emily Davis (employee 5) left the company. Her direct reports move to Brandon Gonzalez, the Marketing Director (employee 21), effective today.
Writes & indexes employees - Medium
The Atomic Stock Transfer
Warehouse rebalancing: 50 units of Widget A (product_id 1) move to the Widget C bin (product_id 3). If only one side of the move were saved, inventory counts would be wrong forever - both updates must succeed or neither.
Transactions ecommerce - Medium
Cancel the Order, Cleanly
A customer cancelled order 12 before it shipped. Cancelling means two things at once: its order_items rows are removed, and the order's status becomes 'cancelled' with total_amount set to 0. A crash in between would leave a ghost order.
Transactions ecommerce - Medium
Enroll and Count, Together
Student 1 is joining SQL Mastery (course_id 1). Enrollment touches two tables: a new row in enrollments (enrollment_id 48, semester 'Fall 2024', grade NULL) and the course's enrolled counter in course_enrollment goes up by one. If only one happened, the seat count would lie.
Transactions school - Hard
Calculate Monthly Retention Rate
Product managers need to understand how many users from each month return the following month.
JOINsAggregation ecommerce - Hard
Year-Over-Year Revenue Growth Analysis
Finance needs a report showing how each product category's revenue has grown compared to the previous year.
SubqueriesWindow functions ecommerce - Hard
Department Salary Median (No MEDIAN Function)
Google interviews often test whether you can implement statistical functions manually when they're not built-in.
JOINsAggregation employees - Hard
Cross-Category Shopping Behavior
The recommendation engine team wants to analyze how many product categories each customer shops from per month.
JOINsAggregation ecommerce - Hard
Full Organizational Hierarchy Depth
The enterprise team needs a complete organizational chart showing each employee's full reporting chain up to the CEO.
JOINsSubqueries employees - Hard
Detect Overlapping Room Bookings
The booking system needs to prevent double-bookings by detecting when room reservations overlap.
JOINs ecommerce - Hard
Longest Winning Streak in Games
Sports analytics needs to find each player's longest consecutive winning streak.
AggregationSubqueries ecommerce - Hard
Calculate CAGR (Compound Annual Growth Rate)
Investment analysts need to calculate the compound annual growth rate of revenue over multiple years.
AggregationSubqueries ecommerce - Hard
Calculate User Session Duration
Product analytics wants to measure average session length by calculating time between first and last event.
AggregationSubqueries ecommerce - Hard
Calculate Reorder Point for Inventory
Supply chain needs to determine when to reorder products based on average daily sales and lead time.
SELECT & filtering ecommerce - Hard
Fuzzy Product Name Matching
Data cleaning team needs to find near-duplicate product names that might be the same item.
JOINsAggregation ecommerce - Hard
Monthly Signup Cohort Retention
Growth team needs a cohort analysis: group customers by signup month, then track what % placed an order in subsequent months.
JOINsAggregation ecommerce - Hard
Cumulative Salary Distribution
Compensation analysts want to see what percentage of employees earn less than or equal to each salary level.
AggregationSubqueries employees - Hard
Detect Consecutive Price Increases
Trading analysts want to identify the longest streak of consecutive daily price increases.
AggregationSubqueries ecommerce - Hard
Multi-Metric Executive Dashboard
The CEO wants a single-query dashboard showing key business metrics.
JOINsAggregation ecommerce - Hard
Generate Fibonacci Sequence with SQL
Can you generate the Fibonacci sequence using only SQL? This is a fun brain teaser that tests recursive CTE mastery.
SubqueriesCTEs employees - Hard
Rebuild the Order Totals
An outage corrupted some order totals. The source of truth is order_items: each order's true total is the sum of quantity times the product's current price.
Writes & indexes ecommerce - Hard
Remove the Ghost Students
An import bug created student accounts that were never enrolled in anything. Compliance wants them gone.
Writes & indexes school - Hard
Index Only What You Query
The ops dashboard polls pending orders by date every few seconds. Pending orders are a tiny slice of the table - indexing everything is waste.
Writes & indexes ecommerce - Hard
Upsert the Stock Count
The nightly warehouse feed reports Widget B (product_id 2) at 450 units. The feed can't know whether a product already has an inventory row - your statement must handle both cases.
Writes & indexes ecommerce - Hard
Drop the Legacy Catalog
Licensing for the pre-1980 catalog expired at midnight. Every track on those albums has to go.
Writes & indexes music - Hard
The Reversible Experiment
Finance (department_id 5) gets a confirmed $1,000 raise per person. While you're in there, an analyst wants to trial-run doubling every salary - but that experiment must NOT survive.
Transactions employees