How to Configure Materialization in dbt: Syntax and Examples
In dbt, you configure materialization by setting the
materialized property in your model's config block or in the dbt_project.yml file. Common materializations include table, view, and incremental, which control how dbt builds and stores your models.Syntax
To configure materialization in dbt, use the config function inside your model SQL file or set it globally in dbt_project.yml. The key property is materialized, which accepts values like table, view, incremental, or ephemeral.
- materialized: Defines how the model is built and stored.
- config block: Used inside model files to set materialization per model.
- dbt_project.yml: Used to set default materialization for all or specific models.
sql
/* Inside a model SQL file */ {{ config(materialized='table') }} SELECT * FROM source_table
Example
This example shows how to configure a model to be materialized as a table using the config function inside the model file. The model will create a physical table in the database when run.
sql
{{ config(materialized='table') }}
SELECT id, name, created_at
FROM raw.customers
WHERE active = trueOutput
Running this model will create a table named after the model file containing only active customers with columns id, name, and created_at.
Common Pitfalls
Common mistakes when configuring materialization include:
- Forgetting to use the
configfunction inside the model file, causing dbt to use the default materialization. - Setting materialization in
dbt_project.ymlbut with incorrect model path selectors, so the config does not apply. - Using
incrementalmaterialization without defining theunique_key, which is required for incremental builds.
sql
/* Wrong: Missing config, defaults to view */ SELECT * FROM raw.orders /* Right: Explicitly set materialization */ {{ config(materialized='table') }} SELECT * FROM raw.orders
Quick Reference
| Materialization Type | Description |
|---|---|
| table | Creates a physical table in the database. |
| view | Creates a database view, which is a saved query. |
| incremental | Builds the model incrementally, adding new data only. |
| ephemeral | Does not create a table or view; inlines SQL in dependent models. |
Key Takeaways
Set materialization using the config function inside model files or in dbt_project.yml.
Common materializations are table, view, incremental, and ephemeral.
Incremental materialization requires a unique_key to work correctly.
Use dbt_project.yml to set default materializations for multiple models.
Always verify your model paths and config syntax to avoid misconfiguration.