DT8: Advanced SQL for analysis

Lesson 1 of 5 · reading 15–25 minutes; practice and project time is on the module page

Readable queries with CTEs

🎯You'll be able to

Break a query into named steps with common table expressions (CTEs), check each step, and write SQL others can review.

🏠The everyday picture

A good recipe lists steps: soak, grind, ferment, cook. A recipe written as one long sentence might be right, but nobody can check it or find the step that went wrong.

📘What it really is

sql with delivered as ( select * from marts.fct_order_lines where status = 'delivered' ), by_store_product as ( select store, product_key, sum(net_amount_paise) as rev from delivered group by store, product_key ) select * from by_store_product order by rev desc;

📝A worked example

Input: run the query above against the solution's warehouse, then check the first step with select count(*) from delivered inside the same with.

Expected output: 8,765 delivered lines, then one row per store and product, led by Sugar 1 kg (SKU-138) at Hadapsar. Breaking the query into steps made each count easy to check.

🌍Where it's used

📝Case scenario

An analyst's 200-line query for quarterly churn was copied into five reports. A reviewer asked where cancelled subscriptions were removed; nobody could tell. Rewritten as six named CTEs, the review found cancelled subscriptions were removed twice, inflating churn.

🖱️Try it

Rewrite this as CTEs: "net revenue per store per weekday, only for Saturdays and Sundays", joining fct_order_lines to dim_date. Success: three steps (filter, join, aggregate), each one you can count.

⚠️Common mistakes

🛠️For your project

Project 3's dashboard queries read the marts; writing your own checks of its numbers in CTEs makes them easy to review.

✅Quick check

What does a CTE do?

Show the answer

Gives a step of a query a name, so later steps can read from it.

How do you check a long query?

Show the answer

Count the rows of each step and compare with what you expect.

← BackDT8
ProLearners Assist