A step-by-step walkthrough of building a dbt project, with advice on what each layer is for and how to choose how each model is stored.


The Big Picture

A dbt project turns raw data into tables people can trust. It does this in stages, and by convention each stage has one job. Data only flows one way, from raw to finished: staging models read the raw tables with source()and every later model builds on earlier ones with ref().

Typical dbt layer structure

If you use the bronze, silver and gold names, staging and base roughly cover the step from bronze to silver, intermediate is silver and marts are gold. However, some teams name these differently and being consistent matters more than the names.

Not every project needs every layer. If your raw data is already flat, skip base. If the table is small, doesn't require a lot of cleaning and there is no need to normalize it, skip intermediate. Add a layer when it has a job to do, not because the diagram has a box for it.


What each layer is for

Sources

Purpose: declare the raw tables dbt reads from but does not build.

What goes in: database, schema and table names, column descriptions, not_null tests on key columns, and freshness thresholds (is new data actually arriving?).

What stays out: any transformation.

Why bother: if the raw table ever moves, you change one file. You also get a tested, documented starting point.

Staging

Purpose: one staging model per source table, a clean and predictable front door.

Do: select the columns you need, rename them, cast simple types.

Do not: join, aggregate or apply business logic.

Storage: view. It costs nothing to store and always reflects the raw table. Many teams give staging its own schema to keep it apart from finished tables.

Base

Purpose: the heavy structural work raw data needs before it is usable: unnesting JSON, flattening arrays, pivoting key-value pairs into columns, removing duplicates and adding a surrogate key.

Output (example): one row per real-world thing (an event, an order line) with real columns and real data types.

Do not: apply business rules or join to other sources.

Storage: table at first, then incremental once data volume makes full rebuilds slow. If the raw shape is deeply nested, split base into several models (for example unnest level one, unnest level two, pivot) so each step is easy to preview and debug.

Intermediate

Purpose: turn clean rows into the building blocks of analysis.

  • Facts are things that happened: events, transactions, measurements. They are narrow and have many rows.
  • Dimensions describe the things facts refer to: customers, products, locations. They usually are wider (more columns) and have fewer rows.

Keep keys consistent so facts and dimensions join cleanly.

Storage: facts are usually incremental (they grow and rarely change). Dimensions are usually a table, or a snapshot if you need to track how attributes changed over time.

Marts

Purpose: the finished, business-facing models. A mart answers a question someone actually asks. It joins facts and dimensions, applies business rules and aggregates.

Naming: name the folder after the question or problem (for example late_deliveries), not after the source system.

Storage: table by default, since people and BI tools query these often. Use a view only if it is cheap and must always be live, as tables are generally cheaper to store nowadays. This is also where documentation effort pays off most, because this is what people see.


Choosing how to store a model

dbt calls this materialization: whether a model is built as a view, a table or something else. The SQL is the same, but the trade-off between storage, speed and freshness is different.

Different model types in dbt

How to decide

Ask these questions to help choose a model type:

  1. Is it only renaming or lightly cleaning? Use a view.
  2. Is it slow to query or queried often? Use a table.
  3. Does a full rebuild take too long or cost too much and does new data mostly add rows? Use incremental.
  4. Does anyone need to know what an attribute used to be? Use a snapshot.
  5. Is it a small piece of logic used in one or two places? Use ephemeral, or just a CTE.

A good rule of thumb: start with a view or a table, and move to incremental only when you can say why. Incremental runs faster, but takes longer to get right.


Where to set your model in dbt

Set defaults per folder in dbt_project.yml:

YAML

Additionally, you can override for one model with a config block at the top of its .sql file:

SQL

If several projects share one repo, either nest the folder settings under the right project name or use config blocks in each model.


Step-by-step: building a project

The example below uses the TfL BikePoint API as the source. The TfL BikePoint API is a free REST web service provided by Transport for London (TfL) as part of their Unified API. It delivers live, real-time data on London’s Santander Cycles (hire bike) docking stations.

Phase A: Connect the source

  1. Install packages. Create packages.yml, then run dbt deps in the command bar to install them.
YAML. Make sure to use the package versions that you need, rather than what is in my example.
  1. Generate the source YAML. In analyses/codegen.sql, fill in your schema, database and table:
SQL

Compile the file and copy the YAML it produces. This file is a scratch file, so you never run it as a model.

Click compile and copy the compiled YAML that appears in the command box
  1. Create the sources file. Make models/staging/bikepoint/_bikepoint__sources.yml and paste the YAML in. The leading underscore keeps YAML files at the top of the folder.
  2. Improve the source. Add descriptions, tests and freshness:
YAML
  1. Test the source. Run dbt test and dbt source freshness.

Phase B: Staging

  1. Generate the staging model. In dbt Cloud, click Generate model above the table in the sources file (or use codegen's generate_base_model). You get a standard source CTE, a renamed CTE and a final select. Save the file using the pattern of stg_<source>__<table>.sql.
YAML
SQL. The generated model.
  1. Build and check it. Preview, then build. Confirm the row count matches the raw table.

Phase C: Base

  1. Create the base folder and first model. Make models/base/ and a file, using the pattern of base_<source>__<table>.sql.
Create new folder.
Create new SQL file in the base directory.
  1. Reference staging. Start with a CTE that reads the staging model:
SQL
  1. Add your unnesting. Develop the SQL in Snowflake (or whatever warehouse adapter you're using) first, then paste it in as the next CTE. Preview after each CTE, then build with dbt build --select <model>. If the JSON is nested in several levels, make one model per level, each reading the one before.
  2. Generate the schema YAML (once you are done with your initial unnesting / transformations for base). In analyses/codegen.sql:
SQL
  1. Compile, copy the result, create a schema, such as models/base/_base_<source>__schema.yml and paste the YAML in. Setting upstream_descriptions=true picks up descriptions already written upstream.
  2. You can write descriptions once and reuse them across all of your YAML schema files throughout the project, as long as the exact same fields are reused. To do this, create a markdown (.md) file in models/_documentation/_<source>__docs.md and populate it using this format:
MARKDOWN
  1. Then point each column at its block in the schema YAML as such:
YAML

Reminder: one description can be reused in every model that has the column.


Phase D: Intermediate

  1. Create a folder named for the domain, such as models/intermediate/<source>/.
  1. Build the fact model. It selects the keys, timestamps and measurements from base, using the same pattern each time: a source CTE, a selected_columns CTE, then select *.
  2. Build the dimension model. It selects the descriptive attributes and collapses to one row per entity, with group by all or distinct.
  3. Build the YAML files for each intermediate model. You can generate them the same way as for the base models using codegen.sql and populate them using the same models/_documentation/_<source>__docs.md file.

Phase E: Marts

  1. Create a marts (gold layer) folder. Instead of naming it “Bikepoint”, name it something more relevant to what problem the data is answering, like in this example's case, “broken_docks”.
  2. Build the mart. Create a .sql file for the final gold layer. Typically in it you will join the fact and dimension, apply the business rules, aggregate and name the model after what it contains.
  3. Preview, build and test it.
  4. Generate and populate the YAML file for your marts layer using the same method in other stages.

Phase G: Build and schedule

  1. Assuming you have specified all of your model types in the dbt_project.yml file or in the SQL model files themselves, it is time to do a final build of everything upstream of a mart by running the following command in the Command Bar:

build --select +<your final mart model>

The + means all of the model's parents.

  1. Create the production job. Go to Orchestration, pick your Production environment and create a deploy job.
z
  • Commands: tick Run source freshness, then add dbt build --select +<your final mart model>.
  • Schedule: a cron such as 30 * * * * runs at half past every hour (UTC). Set it a little after your data usually lands.

I recommend the following website to write / test your CRON:

Crontab.guru - The cron schedule expression generator
An easy to use editor for crontab schedules.

AND YOU'RE DONE!


Extras

Folder and naming conventions

  • Prefix models by layer: stg_, base_, fct_, dim_.
  • A double underscore separates the source from the entity: stg_<source>__<table>.
  • Start YAML and markdown files with an underscore so they sort to the top.

Generating Surrogate Keys

Use {{dbt_utils.generate_surrogate_key(['field_1', 'field_2', 'field_3'])}} to generate surrogate keys in dbt!

  • When you need it: Anytime your table is missing a primary key, or you're mashing up data from a few different places.
  • How it works: It strings your chosen fields together and scrambles them with a cryptographic hash to spit out a completely unique ID.
Surrogate key example

Quick checklist

▢ Source declared, with tests and freshness

▢ Staging view built and row count checked

▢ Base models unnest and dedupe, with a surrogate key

▢ Schema YAML and docs written for every model

▢ Fact and dimension built, with a relationships test between them

▢ Snapshot added only if history is needed

▢ Mart named after the question it answers

▢ Materializations set and incremental logic tested

▢ Production job and full-refresh job created

▢ Work merged to the production branch