Course overview/Design queries that survive review1 of 4

Stage the work

Stage the work

Name each query step after what it produces and make its grain visible.

Structure is part of reviewability

A CTE is the unit a reviewer checks. Use one CTE for each logical step - filter, join, aggregate, rank - and name it after the rows it produces. orders_per_customer tells a reader the grain changed. joined does not.

Every CTE should have a one-line grain comment. Preserve the logic while you improve the names: readable structure is not a licence to alter the result. The query in queries/reading-drill/drill-2.sql is correct, but its names hide that fact.

Your task

Restructure drill-2.sql as drill-2-restructured.sql. Replace t1, t2, and final with names that describe their output. Add a grain comment above each CTE, run both files, and confirm the rows are identical.

Check your understanding

  • Why is orders_per_customer a better CTE name than joined for a step that aggregates order lines up to one row per customer?
  • drill-2.sql filters to 2024 in its first CTE, before any join. Why does that ordering matter?
  • You restructure a query's CTE names and add grain comments but change nothing else. What must you still verify before calling the job done?

Do it with your agent

Say next lesson, write the renamed query yourself, then say review my work. The review should reject placeholder CTE names or a restructuring that changes the returned rows.

Sign up to our newsletter

Practical updates on open-source data pipelines, AI analysts, governance, and what we are shipping at Bruin.

The signup form is hosted by Brevo. Allow marketing cookies to load it.