Cover of SQL Interview Questions for Data Engineers by Vincent Charles

SQL Interview Questions for Data Engineers

45 Real-World Practice Problems with Step-by-Step Solutions

45 original SQL interview problems on realistic data, each with a tested, step-by-step solution you can run on your laptop.

By Vincent Charles ยท 168-page 6 x 9 paperback and Kindle

Who it is for

A SQL interview questions book for data engineers, built for the SQL round of the interview. It is written for:

  • Anyone preparing for a data engineering SQL interview who already knows SELECT, WHERE, JOIN and GROUP BY.
  • A data analyst moving into engineering.
  • A software engineer moving into data.
  • A junior data engineer going for a first or second role, or a mid-level engineer who has not written window functions by hand for a while.

What is inside

45 exercises: 10 Easy, 24 Medium and 11 Hard. Page numbers are from the printed paperback. The parts are a grouping for this page only; the printed book is not divided into parts.

Getting started

1. How to use this bookp. 1
  • Who this book is for
  • How data engineering SQL rounds differ
  • How each exercise works
  • Difficulty levels and time boxes
  • Why DuckDB
  • Setting up in five minutes
  • The five datasets
  • Reading the code
2. How SQL interviews for data engineers workp. 6
  • The usual formats
  • What interviewers score
  • The six-step method
  • The logical order of a query
  • Talking while you write
  • How the chapters fit together

Core SQL

3. Joins and aggregationsp. 10, 7 exercises
  • Q01Revenue by product categoryEasyp. 11
  • Q02Customers without a valid orderEasyp. 14
  • Q03Order lines pointing to missing productsEasyp. 16
  • Q04Revenue double counted after a join (fan-out)Mediump. 18
  • Q05Monthly orders by status as columnsMediump. 21
  • Q06Monthly active buyers and repeat rateMediump. 23
  • Q07Products often bought togetherMediump. 26
4. CTEs and subqueriesp. 28, 5 exercises
  • Q08Orders above the customer's own averageEasyp. 29
  • Q09The NOT IN NULL trapMediump. 32
  • Q10First purchase month cohort sizesMediump. 34
  • Q11Daily revenue vs same weekday last weekMediump. 37
  • Q12Roll up revenue through a category treeHardp. 39
5. Window functionsp. 42, 8 exercises
  • Q13Rank products within each categoryEasyp. 44
  • Q14Running total of daily revenueEasyp. 46
  • Q15Top 3 products per category, with tiesMediump. 49
  • Q167-day moving average with missing daysMediump. 51
  • Q17Month-over-month revenue growthMediump. 54
  • Q18Share of category revenue per productMediump. 56
  • Q19First and last action per userMediump. 58
  • Q20Median and 90th percentile trip time per cityHardp. 61
6. Deduplication and the latest recordp. 64, 5 exercises
  • Q21Find exact duplicate rowsEasyp. 65
  • Q22Keep the latest record per customerMediump. 67
  • Q23Collapse near-duplicate events within 5 secondsMediump. 70
  • Q24Why GROUP BY + MAX mixes rowsHardp. 72
  • Q25Delete duplicates in placeMediump. 75

Time, sessions and pipelines

7. Dates and timep. 78, 4 exercises
  • Q26Orders per day, week and monthEasyp. 79
  • Q27Fill missing days with zeroMediump. 82
  • Q28Report UTC events by local business dayMediump. 84
  • Q29Active subscribers on each dayHardp. 87
8. Gaps, islands and sessionsp. 89, 5 exercises
  • Q30Consecutive login streaksEasyp. 90
  • Q31Longest streak per userMediump. 93
  • Q32Sessionize a clickstream (30-minute timeout)Mediump. 95
  • Q33Session metrics: duration, depth, bounce rateHardp. 98
  • Q34Merge overlapping driver shiftsHardp. 101
9. Incremental loads and historyp. 104, 5 exercises
  • Q35Incremental load with a high-water mark and lookbackMediump. 105
  • Q36Upsert changed rows into a target tableMediump. 108
  • Q37Apply a CDC log to get current stateHardp. 111
  • Q38Build an SCD Type 2 history from daily snapshotsHardp. 113
  • Q39Idempotent daily partition rebuildMediump. 116

Quality, the mock round and wrap-up

10. Data quality checks in SQLp. 119, 3 exercises
  • Q40Not-null, unique and accepted-values checksEasyp. 120
  • Q41Reconcile source and targetMediump. 123
  • Q42Freshness and volume anomaly checkMediump. 127
11. Mock interview roundp. 132, 3 exercises
  • Q43Signup-to-purchase funnel with ordered stepsHardp. 132
  • Q44Monthly retention cohort tableHardp. 136
  • Q45Monthly recurring revenue movementsHardp. 140

12. The 12 mistakes that fail SQL roundsp. 145

Appendix

A. Cheat sheetsp. 147

B. Dialect quick referencep. 158

C. Exercises by conceptp. 162

About the authorp. 164

Look inside

Contents page of SQL Interview Questions for Data Engineers
Contents page of SQL Interview Questions for Data Engineers

Q01Revenue by product categoryEasy

"For each product category, what is the total revenue? Revenue is quantity times unit price, over orders that were not cancelled. List every category that has at least one product, and show 0 for a category whose products never sold. Categories with no products of their own (the parent categories) are not listed."

Tables: categories (category_id, category_name, parent_id), products (product_id, product_name, category_id, list_price), orders (order_id, customer_id, order_ts, status), order_items (order_id, line_no, product_id, quantity, unit_price).

Return: category_name, revenue, one row per category, highest revenue first.

Show the approach and solution
  1. In line_revenue, join order_items to orders, drop cancelled orders, and compute quantity * unit_price for each line.
  2. Start the final query from categories and join products with an inner join. This sets the grain: only categories that have products.
  3. LEFT JOIN the line revenue onto the products, so products with no sales stay in.
  4. Group by category and wrap the sum in COALESCE(..., 0).
WITH line_revenue AS (
    SELECT
        oi.product_id,
        -- NULL when the price is unknown
        oi.quantity * oi.unit_price AS revenue
    FROM order_items AS oi
    JOIN orders AS o
        ON o.order_id = oi.order_id
    WHERE o.status <> 'cancelled'
)
SELECT
    c.category_name,
    COALESCE(SUM(lr.revenue), 0) AS revenue
FROM categories AS c
JOIN products AS p
    ON p.category_id = c.category_id
-- LEFT JOIN keeps categories with no sales
LEFT JOIN line_revenue AS lr
    ON lr.product_id = p.product_id
GROUP BY c.category_id, c.category_name
ORDER BY revenue DESC, c.category_name;

Q02Customers without a valid orderEasy

"Which customers have no valid order? An order is valid when its status is anything other than 'cancelled', so a customer whose only orders were cancelled has no valid order either. If the customers table holds the same row twice, show that customer once."

Tables: customers (customer_id, customer_name, email, city, signup_date), orders (order_id, customer_id, order_ts, status).

Return: customer_id, customer_name, ordered by customer_id.

Show the approach and solution
  1. Read every customer from customers.
  2. Keep a customer only when NOT EXISTS finds no order for them with a status other than 'cancelled'.
  3. Use SELECT DISTINCT so a customer row loaded twice comes out once.
SELECT DISTINCT
    c.customer_id,
    c.customer_name
FROM customers AS c
WHERE NOT EXISTS (
    SELECT 1
    FROM orders AS o
    WHERE o.customer_id = c.customer_id
      AND o.status <> 'cancelled'
)
ORDER BY c.customer_id;

Free sample chapter (PDF)

How to use the book and the joins chapter. Free PDF, download it right after you sign up. Signing up joins the dataengineers.club newsletter. Unsubscribe anytime.

Free resources

Companion GitHub repo

Datasets, all 45 solutions and the tests that check them. The companion code on GitHub is free, no signup needed.

Coming soon.

SQL interview practice

Coming soon.

How to use the book

  1. 1Read the question and the expected columns.
  2. 2Close the book, start a timer and write your own query. Use the time boxes in chapter 1.
  3. 3Run it against the practice data and compare your output with the expected rows.
  4. 4Then read the approach, the solution and the edge cases, even if your answer matched. The edge cases are where most of the learning is.

FAQ

What formats is the book in, and what does it cost?

Kindle is $9.99. The 6 x 9 inch paperback is $17.99.

What level is it?

45 exercises: 9 Easy, 25 Medium and 11 Hard. It is written for people who already know SELECT, WHERE, JOIN and GROUP BY and are preparing for a data engineering SQL round, from a first role up to mid-level.

What environment do I need?

Every solution runs locally in DuckDB 2.0.1, which is free and needs no server or account. Where engines differ, the exercises have dialect notes for PostgreSQL, Snowflake, BigQuery and SQL Server, and for MySQL when it matters. Claims that a query "runs unchanged" or "runs as written" are limited to engines that were actually executed: PostgreSQL 17.12 and MySQL 8.0.43. Some solutions and cheat sheets also mention Databricks, only as an engine that supports QUALIFY, not as a fully annotated dialect.

Where is the companion code?

Datasets, all 45 solutions and the tests that check them will be in a public companion repository on GitHub. The repository is coming soon.

Are there cheat sheets?

Yes. Six typographic cheat sheets: SQL order of execution, joins, window functions, interview patterns, date functions, and NULL handling. Letter and A4 PDFs are free: download them right after you sign up. Short HTML references on dataengineers.club are free to read. Licensed CC BY-NC-ND 4.0.

Does the Kindle edition use DRM, and is it in KDP Select?

No DRM. Not enrolled in KDP Select at launch.

About the author

Vincent Charles
Vincent Charles

Vincent Charles is a data leader with experience at Binance and Morpho. He led European data and analytics initiatives at Binance and built the data function from the ground up at Morpho.

He is the founder of Unchain Data (unchaindata.xyz), a platform specializing in blockchain data, education and careers, and DataEngineers.club, dedicated to practical data engineering resources and technical publishing.

His work focuses on bridging the gap between technical concepts and real-world implementation through practical examples, reproducible code and accessible educational content.

XLinkedIn

Get the book

Not on sale yet. Get the newsletter and hear when it launches.