Analytics Engineering · October 13, 2026 · 5 min
From Legacy SQL to Governed Metrics: A Public dbt Refactor
A small, inspectable demonstration of how to turn one monolithic query into tested dbt models and semantic metrics.
By Achmad Nafila Rozie
Important metrics often begin in a single query. The query works, so people reuse it in dashboards and ad hoc analyses. Later, nobody can easily tell which filters are business rules, what grain the result represents, or whether two teams are still calculating the same number.
I built a public dbt refactor project to show one way to make that logic easier to inspect and maintain. It uses the fictional Jaffle Shop and Stripe datasets. This is a technical demonstration, not a client result or proof of commercial impact.
Keep the old answer in view
Refactoring is different from inventing a new metric. The first question is whether the new pipeline reproduces the legacy result where it should. The project uses output comparison alongside dbt tests so changes in business logic can be found and explained.
That comparison matters because a cleaner model is not automatically a correct one. A changed join, filter, or grain can alter the answer while leaving the SQL perfectly valid.
Give each layer one job
The project separates the original query into staging, intermediate, core, and mart models. Staging standardizes source fields. Intermediate models make joins and reusable calculations explicit. Core models hold the durable business entities and facts. Marts provide a shape for downstream reporting.
The value is not the number of layers. It is that a reviewer can see where a definition lives and what would change if a source or rule changes.
Define metrics above the model
Once the underlying grain and calculations are clear, the project defines measures and metrics through the dbt Semantic Layer and MetricFlow. The example includes order counts, completed order counts, and a completed order rate.
A semantic definition should carry business meaning, not just a formula. The team still needs to agree on eligibility, time windows, ownership, and where a metric should or should not be used. Those decisions are part of the handover, not details to hide in a dashboard.
What this demonstration does—and does not—show
The repository shows modular refactoring, tests, legacy comparison, and semantic definitions on fictional data. It does not show a production migration, a client outcome, or the reliability of an AI analyst querying those metrics.
The practical lesson is narrower and more useful: before asking more tools to use a number, make the number’s lineage, grain, and meaning explicit enough for a team to inspect.
Explore the repository or see how I can help.