SQL Window Functions Practice Problems: 305 Questions with Solutions
305 SQL window functions practice problems with solutions: RANK, LAG, LEAD, running totals and top N per group. Written in MySQL, judged on hidden datasets.
- Problems: 305
- By difficulty: 1 easy · 126 medium · 178 hard
- Dialect: MySQL
Practise SQL window functions in MySQL 8: ROW_NUMBER, RANK and DENSE_RANK, LAG and LEAD, running totals with SUM() OVER, moving averages and PARTITION BY. These are the questions behind "top N per group", "second highest salary", "consecutive days" and "month-over-month growth". Learn the joins and GROUP BY problems first.
Easy SQL window functions problems
Medium SQL window functions problems
- Quiz Team Standings With Shared Places
- Readings From a Stuck Cold-Storage Sensor
- Last Rider Into the Ropeway Cabin
- Gym Members' First and Latest Branch
- Cloud Kitchen Seven-Day Moving Average
- Largest Debit on Each Savings Account
- Branch Deposits Against the Previous Calendar Month
- Running Wallet Balance After Every Transaction
- Constituency Winners From Booth-Level Counts
- Change Between a Donor's First and Latest Gift
- Best-Rated Product in Each Category
- Customers Whose First Order Used a Coupon
- Monthly GMV Against the Previous Calendar Month
- Customers Who Reordered Within 30 Days
- First Student to Submit Each Assignment
- Students Scoring Above Their Section's Internal Average
- Students Whose SGPA Fell by More Than One Point
- Best-Selling Dish of Each Restaurant
- Month-Over-Month Delivered GMV Change by City
- Customers Whose Second Order Came Within a Week
- Top In-App Spender in Each Region for 2025
- Ranked Tier Demotions Between Weekly Snapshots
- Guild Members Above Their Guild's Average Points
- Each Player's First Store Purchase After Sign-up
- Patients Readmitted Within 30 Days of Discharge
- Most Prescribed Drug in Each Department
- Diabetic Patients Whose Latest HbA1c Improved
- Peak Arrival Hour in Emergency Each Day
- Salary Hike Percentage at the April 2025 Appraisal
- Appraisal Ratings Falling Two Cycles Running
- Top Operators per Shift by Good Output
- Solar Generation Sharp Day-Over-Day Drops
- Top Two Ads by Conversions in Each Campaign
- Month-over-Month Ad Spend Change by Channel
- Top-Earning Driver in Each City for Q1 2024
- Latest Tracking Scan for Each Parcel
- Driver Idle Gaps Longer Than 90 Minutes
- Slowest Endpoint in Each Service
- Customers Contacting Support Again Within a Week
- Agent CSAT Rank Within Each Support Team
- Peak Ticket Hour for Each Day of the Week
- Costliest Rental Listing in Each City
- Vacancy Gaps Between Tenants of a Flat
- Each Broker's Best Month by Deal Value
- Top-Selling SKU in Each Store, Ties Included
- Store Revenue Against the Previous Calendar Month
- Stores Beating Their City's Average in Q1
- Monthly Paid Revenue and Its Change From Last Month
- Top Two Features in Every Pricing Plan
- Upgrades, Downgrades and Lateral Plan Moves
- Each Creator's Most-Liked Post
- Sharp Follower Drops Between Daily Snapshots
- Highest Batting Partnership in Each T20 Match
- Best Bowling Figures of Each Bowler This Season
- Monthly Fantasy Contest Entries and the Change From Last Month
- Most-Streamed Artist in Every Genre
- Classify Every Plan Change as Upgrade or Downgrade
- Monthly Subscription Revenue With a Running Total
- Units Consumed From Cumulative Meter Readings
- Most Recharged Prepaid Plan in Each Circle
- Busiest Calling Hour per Cell Tower
- Prepaid Service Lapses Between Recharges
- Waitlist Positions on a Train per Class
- Top Two Agencies by Commission Each Quarter
- Airbnb: Most-Wishlisted Listing in Each City
- Airbnb: Listings Whose Latest Review Scored Lower
- Amazon: Buy Box Winner for Each ASIN
- Amazon: Kindle Reading Sessions That Ended Behind the Last One
- Amazon: Route Stops Delivered Out of the Planned Order
- Amazon: Straight-Line Distance Driven on Each Delivery Route
- Apple: Category Leaders by Q4 Net App Revenue
- Apple: Genius Bar Repeat Visits Within 14 Days
- Apple: Apple Pay Monthly Volume Change by Country
- Apple: Each Product Line's Share of Store Revenue
- Apple: Running iCloud+ Subscriber Count by Day
- Apple: New and Cumulative Unique Apple Arcade Players by Day
- Dream11: Most-Picked Captain in Every Match
- Dream11: The Moment Each Contest Filled Up
- Dream11: Each Player's Form Over Their Last Three Matches
- Flipkart: Top Three Brands per Category Plus an Others Line
- Flipkart: Running GMV Through the Sale by Category
- Google: Local Guides Whose Ratings Turned Harsher
- Google: Play Installs Removed Within a Week
- Google: Searches Reformulated Within a Minute
- Google: Longest Heartbeat Gap of Each Nest Device
- Google: Cloud Cost Spikes Against the Trailing Week
- Hotstar: Biggest Over-on-Over Jump in Viewers
- Hotstar: Worst Rebuffering CDN and Device in Each City
- Hotstar: Top Two Shows per Language by Unique Viewers
- Hotstar: Final-Day Paid Sign-Ups by Hour With a Running Total
- LinkedIn: Most Common Reaction on Each Post
- LinkedIn: Jobs Reposted Within 30 Days
- LinkedIn: Running Follower Count of Company Pages
- Meta: Last-Click Attributed Revenue by Campaign
- Meta: Advertisers Whose Spend Fell Three Months Running
- Meta: Running Quest Store Revenue per Developer
- Microsoft: Days Between Windows Insider Flights per Channel
- Microsoft: Top Human Contributor per GitHub Repository in 2025
- Myntra: Jeans Buyers Whose Waist Size Changed Between Orders
- Ola: Busiest Hour of the Day at Each Hypercharger
- Ola: New Riders Who Took a Second Ride Within 7 Days
- Ola: Driver-Partners Cleared on All Four Documents
- Ola: Riders Whose Main Ride Moved From Auto to Cabs
- Paytm: Runner-Up Movie by Seats Sold in Each City
- Paytm Money: SIPs That Bounced Twice in a Row
- Paytm: Busiest Day for Each EDC Card Machine
- Paytm: Mobile Numbers That Switched Operator Between Recharges
- Paytm: Merchant Days When QR Collections Fell by More Than Half
- PhonePe: Most Frequent UPI Decline Code at Each Remitter Bank
- PhonePe: Top District by Transaction Count in Each State, Q2 2025
- PhonePe: Users Whose First Successful Payment Was at a Merchant
- Razorpay: Leading Card Network in Each Merchant Category
- Spotify: Wrapped Top Artist of Every Listener
- Spotify: Artists Not Touring Their Top Listening City
- Swiggy: Longest Idle Gap in a Partner's Day
- Swiggy: Busiest Instamart Store per City Each Month
- Swiggy: Swiggy Money Debits That Overdrew the Wallet
- Uber: Uber Eats Orders Handed to Another Courier
- Uber: Uber Pro Leaderboard Around Driver 107 in Pune
- Uber: Back-to-Back Trips Starting in the Last Drop Zone
- Walmart: Close-Then-Open Shifts With Under Ten Hours' Rest
- Walmart: Each Store's Sales Gap to Its Region's Leader
- Zomato: Best-Rated Dining Spot in Each Locality
- Zomato: Reviews Far From the Restaurant's Consensus
- Zomato: Blinkit Stock-Outs Lasting a Day or More
- Zomato: Top Intercity Legends Dish in Each Destination City
Hard SQL window functions problems
- Median Delivery Time of Each Restaurant
- Top Three Run Totals in Every League Team
- Busy Streaks at the Book Fair
- Rapid Repeated UPI Transfers: a Fraud Signal
- Longest Run of Consecutive Missed Loan Instalments
- Median Card Spend by Merchant Category
- Top Two PSP Handles by Monthly UPI Volume
- Days From Account Opening to a ₹1 Lakh Balance
- Wards With Complaint Streaks of Three Days or More
- Reservation Holders to Notify After Today's Returns
- First Day a Member's Fine Balance Reached ₹500
- Median Days to Close Service Requests by Department
- Blocks of Three or More Free Adjacent Concert Seats
- Shopping Sessions Abandoned After Add to Cart
- Median Delivery Days per Courier Partner
- Top Three Sellers per Category in Q4, With Ties
- Longest Daily Selling Streak per Seller
- The Redemption That Exhausted Each Coupon Budget
- Longest Daily Learning Streak of Each Learner
- Median CGPA of Each Branch
- Top Three Scores in Each National Mock Test
- Day Each Branch Crossed 50% Placement
- Longest On-Time Delivery Streak of Each Rider
- Dark Store Daily Orders, Zero Days Included
- Rider Cash-in-Hand Between Deposits
- Top Two Restaurants per Cuisine by Repeat-Customer Rate
- Longest Daily Login Streak per Player
- Battle Pass Race to Tier 30, Season by Season
- Peak Concurrent Game Sessions per Server Region
- Median Completed Match Duration by Game Mode
- ICU Over-Capacity Streaks
- Median Length of Stay by Ward
- Patients With Three or More No-Shows in a Row
- Daily Admissions With Quiet Days and a Running Total
- Unplanned Absence Streaks of Three Working Days
- Median CTC for Each Job Level
- Leave Ledger Entries That Took the Balance Negative
- Longest Defect-Free Batch Streak per Line
- Merged Alarm Downtime per Machine
- Sustained Vibration Breach Episodes
- Median EV Charging Session Length by City
- Solar Daily Output With Missing Days Filled
- Service-Due Day in Each Maintenance Cycle
- First-Touch vs Last-Touch Revenue by Channel
- Streaks of Three or More Overspent Days
- Ad-Click Sessions per Shopper
- Median Daily Spend of Each Channel
- Each Driver's Longest Streak of Active Days
- Rider App Sessions and Booking Conversion
- The Day Each Driver Hit the Monthly ₹10,000 Target
- Median Pickup-to-Drop Minutes in Each Delivery Zone
- 90th Percentile API Latency per Endpoint
- Longest Streak of Clean Deploys per Service
- Total Outage Minutes per Service With Overlaps Merged
- Gaps in the On-Call Rota
- Sessionise API Calls and Count Server Errors
- Median Time to Resolve Incidents by Severity
- Tenants Late on Rent Three Months Running
- Median Registered Rate per Sq Ft by Locality
- Top Two Agents per City by Commission, Ties Included
- FIFO Valuation of the Stock Left on Hand
- Longest Consecutive Stock-Out Run per SKU
- First Day a SKU's Stock Falls Below Its Reorder Point
- Median Supplier Lead Time From Goods Inward
- User Sessions From Thirty-Minute Event Gaps
- Longest Daily Usage Streak per User
- Median Days From Trial to Paid by Acquisition Channel
- Average Reply Time in Direct Messages
- Longest Daily Posting Streak per Creator
- Median Likes per Creator
- App Sessions From the Event Stream
- Longest Winning Streak of Each Football Club
- The Over in Which Each T20 Innings Passed 100 Runs
- Median Fantasy Points per Gameweek by Player Role
- Days Each Player Was Out Injured, Merging Overlapping Records
- Orange Cap Leader After Every Match Day
- Binge-Watch Runs of Three or More Episodes
- Longest Daily Listening Streak per Listener
- Median Session Length by Device
- Daily Streams in an Album's First Week, Zero Days Included
- Longest Streak of Heavy Data Days
- Feeder Downtime After Merging Overlapping Outages
- Median Completed Call Duration per Tower
- Top Two Data Consumers per Circle, Ties Included
- Electricity Bill Settlement From Part Payments
- Flights Delayed Three or More Days in a Row
- Peak In-House Guests per Hotel
- Median Departure Delay per Airport
- App Sessions That End in a Hotel Booking
- Date Each Frequent Flyer Qualified for Gold
- Airbnb: Longest Open Stretch on Each Listing's Calendar
- Airbnb: Collapse Nightly Prices Into Rate Periods
- Airbnb: Back-to-Back Stays Merged Into Trips
- Airbnb: Hosts With Three Cancellations Inside 30 Days
- Airbnb: Attribute Each Booking to Its Last Search
- Amazon: Clearing Price of Each Sponsored Products Auction
- Amazon: First Day Each Seller Breached the 60-Day Order Defect Rate
- Amazon: Package Dwell Time at Each Facility Visit
- Amazon: AWS Promotional Credits Applied Month by Month
- Amazon: Suggested Subscribe & Save Cadence From Reorder Gaps
- Amazon: Packing Station Backlog Carried Hour to Hour
- Apple: Subscription Billing Lapses Recovered in the Grace Period
- Apple: Devices That Moved to an Older iOS Version
- Apple: Apps Breaking Into Their Category's Top Three
- Apple: Launch-Day Pre-Orders Filled Strictly in Queue Order
- Apple: Apple Pay Rolling Seven-Day Fraud Rate
- Dream11: Contest Prizes When Tied Teams Share a Rank
- Dream11: Longest Run of Matches With the Same Captain
- Dream11: Top Three Users by Net Winnings in Each Sport
- Dream11: Contest Winners From Player Points With C and VC Boosts
- Dream11: Biggest Live Leaderboard Climb of Each Team
- Flipkart: SuperCoins Left in Each Earn Batch After FIFO Burns
- Flipkart: Month-to-Month Sales Quartile Movement Matrix
- Flipkart: Sale-Acquired Buyers Who Came Back for the Next Sale
- Flipkart: Unscanned Ekart AWB Numbers as Ranges per Hub
- Flipkart: First Day a Seller Logged Three Returns in Seven Days
- Flipkart: How Often Each Product's Buy Box Changed Hands
- Google: Play Service Fee and the Purchase That Crossed the Tier
- Google: Cloud VM Cost With Machine Types Filled Forward
- Google: Prorated Workspace Seat-Days for June 2025
- Google: Longest YouTube Autoplay Chain in Each Session
- Google: Median First-Reply Time in Gmail Support Threads
- Hotstar: Peak of Three-Sample Smoothed Concurrency per Match
- Hotstar: 90th-Percentile Video Start Time by CDN
- Hotstar: Commentary Feed Switches and Final Language per Viewer
- Hotstar: Deduplicated Watch Minutes Across Overlapping Devices
- LinkedIn: Merge Overlapping Premium Periods Into Spans
- LinkedIn: Top Endorsed Skill per Industry and Its Lead
- LinkedIn: Boomerang Hires in Members' Work History
- Meta: WhatsApp Business Conversation Windows
- Meta: Growth Accounting of Monthly Active Users
- Meta: Each Reels Creator's Percentile Rank Within Their Country
- Meta: The Day Each Campaign Exhausted Its Lifetime Budget
- Microsoft: Teams Attendees Present for at Least 75% of a Meeting
- Microsoft: Xbox Hunters With the Most Rare Achievements
- Microsoft: Bing Search Sessions That Ended Without a Click
- Microsoft: Game Pass Win-Back Rate by Cancellation Month
- Myntra: Each Brand's Share of Its Category in the EORS
- Myntra: Each Brand's Three Most-Wishlisted Styles in One Row
- Myntra: Sizes Over-Represented in Size Returns per Article Type
- Myntra: The Few Brands Making Up 80% of Each Category's Sale Revenue
- Myntra: Serial Returners by Their Last Five Delivered Orders
- Ola: Scooters Behind Their Model's Newest Firmware
- Ola: Each Scooter's Opening and Closing Readings per Day
- Ola: Peak Simultaneous Charging Sessions at Each Station
- Ola: First Fault Code After Each Software Install
- Paytm: Daily Seats Sold for Every Day of a Movie's Run
- Paytm: Return Flights Booked Within Ten Days
- PhonePe: Users Paying Three New Payees Within One Hour
- PhonePe: Failed UPI Payments Recovered by a Retry, per Bank
- PhonePe: Bank Downtime Runs From Consecutive Technical Declines
- PhonePe: Merchant-Spend Quartiles of Users in Each City, March 2025
- PhonePe: Districts Whose State Rank Rose Every Quarter of 2024
- PhonePe: Merchants Earning Half Their Takings From Three Customers
- Razorpay: Payments Settled After Their T+N Working Day
- Razorpay: Orders Rescued by Switching Payment Method
- Razorpay: Queued Payouts Rejected for Insufficient Balance
- Razorpay: Merchants Whose Weekly Success Rate Fell 10+ Points
- Spotify: Family Plans That Ever Had Over Six Members at Once
- Spotify: Weekly Top 3 Chart With New, Re-Entry, Up and Down Labels
- Spotify: Pro-Rata Royalty Pool Payouts for June 2024
- Spotify: Listeners Whose Top Genre Changed From Q1 to Q2
- Swiggy: Third Delivered Order of Each New Customer
- Swiggy: Restaurant Offline Minutes Within Opening Hours
- Swiggy: Kitchens Slowing Down Three Weeks Running
- Swiggy: Instamart Items Most Often Bought Together
- Swiggy: Instamart Picking Bags From Order Lines
- Uber: Longest Surge Episode in Each Zone
- Uber: Split Fare Shares to the Paisa
- Uber: Trip Event Logs That Break the State Machine
- Uber: Which Promo Gets Credit for a Rider's First Trip
- Walmart: Walmart+ Membership Spells, Bridging Short Lapses
- Walmart: Truck Routes Rebuilt From Store Geofence Pings
- Walmart: Understaffed Stretches on the Sales Floor
- Walmart: Median Minutes From Shelf Gap to Refill by Department
- Zomato: Live Menu Rebuilt From the Latest Approved Edits
- Zomato: Most-Loved Dish of Each Restaurant and Its Complaints
- Zomato: Progressive Commission on Each Restaurant's Monthly Sales