How to Use Tags in dbt for Model Organization and Selection
In dbt, you use
tags in your model configuration to label models with keywords. These tags help organize models and allow you to run or test specific groups by referencing their tags with commands like dbt run --select tag:your_tag.Syntax
To add tags to a dbt model, include the tags key inside the model's config block in the model SQL file or in the dbt_project.yml file. Tags are listed as an array of strings.
Example parts:
config: A function to set model properties.tags: A list of strings labeling the model.
sql
{{ config(tags=['tag1', 'tag2']) }}Example
This example shows how to tag a model and then run only models with that tag.
First, add tags in the model file. Then run dbt selecting models by tag.
sql
-- In models/my_model.sql {{ config(tags=['finance', 'monthly']) }} select * from raw_data.transactions where date >= '2024-01-01'; -- Command to run only models tagged 'finance' dbt run --select tag:finance
Output
Running with dbt=1.4.0
Found 1 model, 0 tests, 0 snapshots, 0 analyses, 0 macros, 0 operations
19:00:00 | Concurrency: 1 threads
19:00:00 |
19:00:01 | 1 of 1 START table model dbt_project.my_model................ [RUN]
19:00:05 | 1 of 1 OK created table model dbt_project.my_model........... [OK in 4.0s]
Completed successfully
Common Pitfalls
Common mistakes when using tags in dbt include:
- Not using the
configblock correctly inside the model file. - Forgetting to use
--select tag:tag_namewhen running commands to filter by tags. - Using tags inconsistently or with typos, which causes models to be missed during selection.
Always double-check tag spelling and placement.
sql
-- Wrong: tags outside config block -- models/wrong_model.sql {{ tags=['sales'] }} select * from raw_data.sales -- Right: {{ config(tags=['sales']) }} select * from raw_data.sales
Quick Reference
| Feature | Usage | Example |
|---|---|---|
| Add tags to model | Use config(tags=[...]) in model SQL | {{ config(tags=['tag1', 'tag2']) }} |
| Run models by tag | Use dbt run --select tag:tag_name | dbt run --select tag:finance |
| Multiple tags | List multiple tags in array | {{ config(tags=['tag1', 'tag2']) }} |
| Check tags | Use dbt ls --select tag:tag_name to list models | dbt ls --select tag:monthly |
Key Takeaways
Use the config block with tags array to label dbt models.
Run or test models by specifying tags with --select tag:tag_name.
Tags help organize models logically and improve workflow control.
Always place tags inside the config function in model files.
Check tag spelling carefully to avoid missing models during selection.