By role
SQL interview questions for data analysts
Data analyst screens lean on the same core: joins that keep the right rows, aggregates at the right grain, window functions for ranking and running totals, and the NULL traps that quietly change an answer.
What to get right
- Say the grain of the result out loud before you write a line: one row per what?
- Check what happens to groups with no rows. Interviewers add one on purpose.
- Use RANK when ties matter and say why you chose it over ROW_NUMBER.
Group and aggregate Read the lesson
- Billed, paid and outstanding by industryFinance wants a receivables summary by customer industry, using every invoice in invoices.
- First and last product name and launch date by categoryThe catalog team is tidying the product list and wants a quick profile of each category.
- First response times by priorityThe support lead wants a response-time summary for each ticket priority, using every row in tickets.
- Five-star trips per driver in June, idle drivers includedThe community team wants to thank drivers for great service and also see who got no recognition. For June 2025, count each driver's five-star trips.
- Monthly money in, money out and net flowFinance wants a monthly cash-flow table for the whole bank, using every row in transactions.
- Orders, coupon orders and customers by channelThe marketing lead wants one summary line per sales channel. Use every row in orders, whatever its status.
- Plays, listeners and hours by genreThe content team wants one line of listening stats per genre. A play belongs to the genre of its track's artist.
- Revenue by category, including empty onesFinance wants revenue for every product category in the catalog. Revenue is quantity * unit_price from order_items, counting completed orders only.
- Accounts with a high average invoiceThe revenue team wants a shortlist of big-ticket accounts. Use every invoice in invoices, paid or not.
- Artist catalog size and 2025 releasesThe label relations team wants a status line for every artist: how big the catalog is, and how much of it is new this year.
- Average order value by channelThe growth team tracks average order value (AOV) for each sales channel. Only completed orders count.
- Average rating per city, weighted by tripsThe quality team publishes one rider rating per city. A rider may skip the rating, so rider_rating is NULL on many completed trips.
- Busy accounts in May and the fees they paidThe pricing team is reviewing fees on very active accounts. Look at transactions with posted_at on or after 2025-05-01 00:00:00 and before 2025-06-01 00:00:00.
- Categories behind each agent's unhappy surveysThe support manager is preparing one-to-one meetings. For each agent she wants to see which ticket categories ended in an unhappy customer.
- Completed trips by driver tenure bandThe driver success team wants to know whether newer drivers earn less per trip. Use completed trips only.
- Customers grouped by how many orders they placedThe CRM team wants to split 2025 shoppers into three groups by how often they bought.
- Customers whose every account is closedThe retention team wants a list of customers who have left the bank entirely.
- Fare per kilometre by city and vehicle typeThe pricing team compares how much a kilometre earns in each city for each kind of vehicle. Use completed trips only.
- Resolution speed buckets and satisfactionThe support lead wants to know whether slow resolutions make customers unhappy.
- Riders whose first and last trips are 71 days apartThe lifecycle team wants to study riders who stayed around. For every rider, look at their completed trips and the calendar date of requested_at.
- Share of June plays by deviceProduct wants to know which devices people use for real listening in June 2025.
- Most played genre for each plan and deviceThe playlist team wants to know the most common genre for each kind of listening session.
- Overdue invoices by account managerCollections wants an overdue list by account owner. Today is 2025-06-30 for this report.
- Plan stretches and billing for accounts that changed planCustomer success is reviewing accounts that moved between plans.
- Spend mix by customer segmentThe product team wants to see how each customer segment splits its everyday spending.
- Units sold and units returned by categoryQuality wants to compare how many units each category sold with how many came back.
Joins Read the lesson
- April spend and cost per click for search and socialThe paid team reviews campaigns on the search and social channels for April 2025 (from 2025-04-01 to 2025-04-30 inclusive, by ad_daily.day).
- Email-referred customers and their completed ordersThe lifecycle team wants to see how well the email channel converts. Look at every customer whose referral_source is 'email'.
- Headcount by department, empty and unassigned includedThe people team needs a headcount table that accounts for every department and every person. Count current employees only: those whose termination_date is NULL.
- Plays in the first two weeks for April joinersThe growth team measures early engagement. Take every listener whose joined_on is in April 2025 (2025-04-01 to 2025-04-30 inclusive).
- Recurring revenue by plan on a given dayFinance asks what the subscription book looked like on 15 March 2025.
- Refund value of wrong-item returns by categoryCustomer care is costing out "wrong item" returns. Look at rows in returns whose reason is 'wrong_item'.
- Sign-ups per campaign who placed a large orderMarketing wants to know which campaigns bring in big spenders.
- Trips from brand-new riders, by cityThe city managers want to know how much of each city's volume comes from new riders.
- Urgent email and phone tickets by team, with unassignedThe support lead reviews urgent tickets that came in by email or phone (priority = 'urgent' and channel is 'email' or 'phone') and how happy customers were.
- Completed trips for every city and vehicle typeOperations is building a grid for a dashboard: one row for every combination of a city and a vehicle type, so that empty cells are visible.
- Each December rider's most recent completed tripRider care is writing to everyone who signed up in December 2024 (riders.signed_up_on from 2024-12-01 to 2024-12-31 inclusive) and wants to mention their...
- Free and paid listeners per genreThe product team wants to know which genres reach people on the free plan and which reach paying people.
- Kitchen revenue by customer country, four tablesThe merchandising team wants to know where the Kitchen range sells. A customer's country is customers.country.
- Listeners who played both jazz and folkEditorial wants to build a crossover playlist and asks how many listeners already enjoy both worlds, by country.
- Organic sign-ups during each campaign's runThe growth team wants a rough sense of the background sign-up rate while each campaign ran. A campaign was live from started_on to ended_on, both days included.
- Premium customers, accounts and money inRelationship managers review every customer in the 'premium' segment. A customer can have several accounts, and each account has many transactions.
- Spending by merchant partner group, NULL merchants includedPartnerships keeps a small lookup of merchants and the group each belongs to.
- Tickets per response band from a band lookup tableThe support team reports how fast it answers. The response time of a ticket is the time from created_at to first_response_at, in minutes (fractions allowed).
- Tracks and plays per jazz artist without double countingThe label relations team reviews every artist whose genre is 'jazz'. For each one they want the size of the catalog and how much it is played.
- Units ordered and units returned per orderOperations reviews every completed order placed in August 2024 (from 2024-08-01 00:00 up to, but not including, 2024-09-01 00:00) for returns.
- Daily spend against sign-ups for one campaignThe growth team is reconciling two sources for the "Family meals video" campaign (campaign_id = 3) in May 2025: the ad platform's daily spend (ad_daily)...
- Salary in effect at review time, by ratingThe people team asks whether higher ratings go with higher pay.
- Spend and sign-ups per campaign from two sourcesThe marketing report builds one row per campaign from two separate sources: total spend from ad_daily, and the number of sign-ups credited to the campaign...
Ranking and top N Read the lesson
- Five longest-serving employees, keeping ties at the cut-offThe people team is planning a service-award event for the longest-serving current employees (termination_date is NULL). Rank them by hire_date, earliest first.
- Pay ladder with RANK and DENSE_RANK side by sideThe people team is drawing a pay ladder for every department and cannot decide how to number tied salaries, so they want both numberings next to each other.
- Products at the three highest price pointsMerchandising is building a "premium shelf" from the products at the three highest distinct list_price values in the whole catalog.
- Three slowest first responses in each channelThe support lead is reviewing the slowest first replies.
- Top earner in each department, with a tie-breakerThe people team wants a one-line profile of the best paid current employee in every department.
- Best seller on each sales channel in the first quarterThe channel managers want to know what sold best on their channel in the first quarter of 2025.
- Driver rating leaderboard, unrated drivers lastThe operations team of the pilot city (the city with city_id 1) wants a leaderboard of its drivers: every driver whose home city (drivers.city_id) is 1.
- Each customer's largest single expense, with tie-breakersThe fraud team wants to see each customer's biggest purchase. An expense is a transaction with a negative amount whose category is dining, groceries or travel.
- Employees in the top quarter of pay, by PERCENT_RANKCompensation wants to review the best paid people in each department. Use current employees only (termination_date is NULL) who belong to a department.
- Genre of each listener's first playThe growth team wants to know which genre hooks new listeners.
- Listener quartiles by May listening timeThe product team wants to compare heavy and light listeners.
- Months each merchant ranked in the top three for spendThe cards team tracks which merchants dominate everyday spending. A transaction counts as everyday spending when its category is dining, groceries or travel.
- Second highest salary in each departmentThe people team is checking pay bands and wants the second highest salary in every department, looking only at current employees (termination_date is...
- The third longest completed trip in each cityOperations is reviewing long-distance trips and wants the third longest completed trip in every city, as a row position: sort the city's completed trips...
- Top three drivers in each city, ties at third place keptThe driver community team gives a monthly shout-out to the busiest drivers in each city.
- Top three products in each category, with tiesMerchandising wants the best sellers in each category. Rank products within their category by units sold on completed orders, most units first.
- Top two agents per team by satisfaction, with tie-breakersThe support lead wants to recognise the two happiest-making agents in each team. Use the surveys in satisfaction joined to their ticket's agent_id.
- Top two artists each month by listening timeThe editorial team picks two featured artists per month for the home screen.
- How far each artist climbed or fell from April to MayThe charts team publishes a monthly artist ranking and wants to show movement.
Running totals, LAG and LEAD Read the lesson
- Cumulative revenue by day, including quiet daysThe finance team plots cumulative purchase revenue for June 2025. The chart needs one point for every calendar day, even a day with no purchases.
- Invoices where the amount changedFinance wants to review every price change. Find each invoice whose amount is different from the same account's previous invoice.
- Percentage change from the previous salaryThe people team is reviewing pay changes since the start of 2024.
- Plays that were immediately replayedThe recommendations team wants to find tracks that listeners loved enough to play again straight away.
- Running balance for one bank accountA customer disputes their January statement for account 20. Rebuild it with a running balance. List every transaction on account 20 posted before 2025-02-01.
- Running earnings for two driversThe driver-support team is looking at how earnings build up for two long-serving drivers, driver 5 and driver 13.
- Dining spend that restarts each monthA budgeting feature shows how much a customer has spent on dining so far this month, and the figure starts again at the beginning of each month.
- Each day's rate next to the month-end rateAn analytics engineer is building a table that shows each exchange rate next to the closing rate of its month.
- Hours since the customer's previous ticketThe support lead wants to know how quickly customers come back.
- June purchases compared with the first purchaseThe lifecycle team wants to see how a customer's big June orders compare with the very first order they ever placed.
- Record click days with a running maximumThe paid-media team celebrates each campaign's best day so far. For every campaign, track its high-water mark of daily clicks during June 2025.
- Running count of distinct buyers by first purchase monthThe growth team charts how many different people have ever bought in the app. A user is a buyer once they have at least one purchase event.
- Time until a rider requests again after cancellingThe rides team wants to know whether riders who cancel try again soon.
- Products that make up 80 percent of revenueMerchandising wants a Pareto list: the smallest set of best-selling products that together reach at least 80% of completed-order revenue.
- Rolling seven-day spend when days are missingA pacing report shows, for campaign 1, how much it spent over the last 7 calendar days. A campaign that did not serve ads on a day has no row for that day.
- Seven-day moving average of sign-upsThe growth team charts daily sign-ups with a 7-day moving average. Build the June 2025 numbers.
NULL handling Read the lesson
- Customer contact labels with missing emailsThe email tool wants one display label per customer.
- Customers by referral source, with unknown shownMarketing wants a headcount of customers by where they came from.
- Invoices issued, paid and unpaid by industryCollections wants a quick count per industry. An invoice is paid when paid_on is not NULL and unpaid when it is NULL.
- Orders that did not use a couponThe marketing team wants to see how many orders were placed without the WELCOME10 coupon.
- Total fare by city, including cities with no completed tripsThe finance team needs the money taken in each city. fare is NULL on any request that was not completed.
- Average fare per request and per completed tripThe city managers compare two averages. fare is only filled in for completed trips, and is NULL for cancelled requests and requests no driver took.
- Average satisfaction score by channelThe support lead wants the average satisfaction score by channel.
- Number campaigns by end date, running ones lastThe campaign dashboard lists campaigns by how recently they ended. Number the campaigns 1, 2, 3, ...
- Tickets by first response time bandThe support lead wants to see how long customers wait for a first reply.
- Tickets per agent, including unassigned onesThe support lead wants the workload on one list: how many tickets each agent has, how many are waiting with no agent at all, and which agents have nothing.
- Riders who got a different driver than last timeMarketplace ops wants to know how often a rider's outcome changes from one request to the next.
Ratios and percentages Read the lesson
- Cancellation rate by cityCity managers want to know how often a ride request ends in a cancellation.
- Cost per click, with zero-click campaignsFinance wants the cost per click (CPC) of every campaign: all the money it spent divided by all the clicks it got, in US dollars.
- Share of revenue by categoryThe merchandising team wants to see how completed sales split across product categories.
- Share of users who purchased, by platformThe product team wants to know what share of users have ever bought something in the app.
- Click-through rate by campaignThe marketing team reports the click-through rate (CTR) of each campaign: all the clicks it received divided by all the impressions it served, over every...
- Driver cancellations among accepted ridesDriver operations wants to know how often a driver backs out after accepting a request.
- On-time payment rate by industryFinance wants to know which industries pay on time. An invoice was paid on time when paid_on is on or before due_on.
- Refund rate by count and by valueFinance tracks refunds in two ways: how many orders were refunded, and how much money they were worth.
- Sign-up to purchase conversion by campaignThe growth team judges each campaign by how many of its sign-ups ever bought something.
- Skip rate by genreThe content team wants to know which genres get skipped. A play is a skip when seconds_played is less than 30. A play of exactly 30 seconds is not a skip.
- Survey response rate and CSAT by teamThe support lead tracks two numbers for every team, and they have different denominators.
- Return rate by product categoryOperations wants to know which categories come back the most. For each category, the return rate is the units returned divided by the units sold.
- Revenue per account, including non-payersLeadership wants the average collected revenue per account for each industry.
- Share of sessions with a search, by platformProduct wants to know how often a visit to the app includes a search. A session is one distinct session_id, and every session belongs to a single user.
- Spending share by category within each segmentThe bank wants to see how each customer segment spends its money.
More for this role
- Agent share of their team's ticketsCTEs and subqueries
- Employees paid above their department averageCTEs and subqueries
- Months billed above the monthly averageCTEs and subqueries
- Average transactions per open accountCTEs and subqueries
- Everyone who reports to a manager, at any depthCTEs and subqueries
- Listeners whose first play was on a speakerCTEs and subqueries
- Orders above the customer's own average orderCTEs and subqueries
- Reporting chain from an employee up to the CEOCTEs and subqueries
- Riders who came back after a driver cancelledCTEs and subqueries
- Ticket categories with an above-average urgent shareCTEs and subqueries
- Buyers whose latest purchase beat their earlier averageCTEs and subqueries
- Campaigns cheaper per sign-up than their channelCTEs and subqueries
- Headcount by level below the CEOCTEs and subqueries
- Average fare for short and long tripsConditional aggregation
- Full-play rate by genreConditional aggregation
- Order status counts per channelConditional aggregation
- Plays per device for each planConditional aggregation
- Products per price band, empty bands includedConditional aggregation
- Rider cancellations per completed trip, by cityConditional aggregation
- Customers who buy in the app but never on the webConditional aggregation
- Listener device habits by planConditional aggregation
- Money in and money out per savings accountConditional aggregation
- On-time, late and unpaid invoices by monthConditional aggregation
- Repeat cart adders who never boughtConditional aggregation
- Requests and completion rate by time of dayConditional aggregation
- First-response SLA by agentConditional aggregation
- Seven-day buyer rate by campaignConditional aggregation
- Active users in the 30 days before a dateDates and time
- Average pickup wait and trip length in minutesDates and time
- Customers by tier on a past dateDates and time
- Listens by hour of dayDates and time
- May trip requests by city, last day includedDates and time
- Monthly cost per click by channelDates and time
- Weekly ticket volume, weeks starting MondayDates and time
- First response within one hour, by channelDates and time
- Listener tenure in whole months by planDates and time
- Overdue invoices as of a fixed dateDates and time
- Subscriptions active on a given dateDates and time
- Live campaign days with no deliveryDates and time
- Month-end balance by account typeDates and time
- Seats on the last day of each monthDates and time
- Quarter-over-quarter invoiced revenuePeriod over period
- Biggest month-over-month spending drop per categoryPeriod over period
- Channel share of ad spend, Q1 against Q2Period over period
- Month-over-month change in invoicingPeriod over period
- Monthly buyers and growth, with gap monthsPeriod over period
- Week-over-week high-priority ticketsPeriod over period
- Year-over-year completed orders by monthPeriod over period
- Artist rank change from May to JunePeriod over period
- New and churned seats by monthPeriod over period
- Year-to-date units against the same period last yearPeriod over period
- Colleagues hired in the same month and departmentSelf joins
- Repeat tickets from the same customer within a weekSelf joins
- Skip-level managers and how many people they coverSelf joins
- Employees paid more than their managerSelf joins
- Products bought together in the same orderSelf joins
- Trips between a rider and a driver they already knowSelf joins
- Users whose carts turn into purchases within 30 minutesSelf joins
- How many drivers in the same city rate higherSelf joins
- Raises of 9.5 percent or more over the previous salarySelf joins
- Agents who got no urgent ticket in AprilRows with no match
- Campaigns that never brought in a paying userRows with no match
- Customers with no completed order in MarchRows with no match
- Products that sold but were never returnedRows with no match
- Accounts billed since May with no paid invoiceRows with no match
- Customers with savings but no open checking accountRows with no match
- Listeners who played no jazz in JuneRows with no match
- Sign-ups who never bought, by sign-up monthRows with no match
- New riders with no completed trip in their first 14 daysRows with no match
- Customers with several accounts under one emailDeduplication and latest row
- Find exact duplicate rows in a raw order loadDeduplication and latest row
- How many rows would deduplication remove?Deduplication and latest row
- Emails shared by accounts that disagree on countryDeduplication and latest row
- Orders by current status from a raw loadDeduplication and latest row
- Repeat tickets from the same customerDeduplication and latest row
- Salary in effect on a date for each employeeDeduplication and latest row
- Revenue to date per customer by sign-up quarterCohorts and retention
- Rolling retention after day 30 by first-order quarterCohorts and retention
- Day 1 and day 7 retention by sign-up monthCohorts and retention
- Listeners who came back after a gapCohorts and retention
- Retention table for months 0 to 3Cohorts and retention
- Weekly sign-up cohorts and next-week buyersCohorts and retention
- Month-one retention by sign-up cohortCohorts and retention
- Month-over-month net revenue retentionCohorts and retention
- Monthly subscription churn rateCohorts and retention
- Customer activation funnel by segmentFunnels
- Ad funnel from impressions to buyers by channelFunnels
- Biggest drop-off step in the ride funnelFunnels
- Conversion between each funnel stepFunnels
- Median hours from sign-up to first purchaseFunnels
- Ordered purchase funnel by platformFunnels
- Purchase funnel by experiment variantFunnels
- Longest run of delivery days per campaignGaps and islands
- Missing inventory snapshot ranges per SKUGaps and islands
- Streaks of four or more days of opening the appGaps and islands
- Longest run of consecutive driver cancellationsGaps and islands
- Merge subscription rows into continuous customer stretchesGaps and islands
- Median listen length, continuous and discreteMedians and percentiles
- Median salary by departmentMedians and percentiles
- 90th percentile trip length by cityMedians and percentiles
- Purchase value spread (interquartile range) by platformMedians and percentiles
- Median dining spend by month, without percentile functionsMedians and percentiles
- Customers by email domainText and set operations
- Names shared by several drivers and ridersText and set operations
- Browse-only sessions by platformText and set operations
- A small data quality test suite as one queryAnalytics engineering
- Current gold customers by region from type 2 historyAnalytics engineering
- Data test for direct buyers with no usable emailAnalytics engineering
- Grain check for a user by day purchase modelAnalytics engineering
- Order copies that arrived more than 12 hours lateAnalytics engineering
- Active accounts and seats per day from subscription datesAnalytics engineering
- Agent by month fact table of tickets created and resolvedAnalytics engineering
- Customer tier at a point in time from type 2 historyAnalytics engineering
- One row per savings account per month, with zero fillAnalytics engineering
- Salary validity ranges built with LEADAnalytics engineering
- Turn stock snapshots into restock eventsAnalytics engineering
- Daily end-of-day balance from transactions with a date spineAnalytics engineering
- Daily stock levels with a date spine and carry forwardAnalytics engineering
- Orders by the customer's tier when the order was placedAnalytics engineering