How to Use source Function in dbt: Syntax and Examples
In dbt, use the
source function to reference raw tables defined in your sources configuration. It takes two arguments: the source name and the table name, like source('source_name', 'table_name'), allowing you to build models that depend on raw data sources.Syntax
The source function in dbt is used to refer to raw data tables defined in your sources configuration. It requires two arguments:
- source_name: The name of the source as defined in your
sources.ymlfile. - table_name: The name of the table within that source.
This function returns a reference to the raw table, which you can use in your SQL models.
sql
select * from {{ source('my_source', 'my_table') }}
Example
This example shows how to define a source in sources.yml and then use the source function in a dbt model to select data from that source.
yaml + sql
# sources.yml version: 2 sources: - name: my_source tables: - name: my_table -- models/my_model.sql select * from {{ source('my_source', 'my_table') }} where status = 'active'
Output
This query selects all rows from the raw table 'my_table' in source 'my_source' where the status column equals 'active'.
Common Pitfalls
Common mistakes when using the source function include:
- Not defining the source and table correctly in the
sources.ymlfile. - Misspelling the source or table names in the
sourcefunction call. - Using
refinstead ofsourcefor raw tables, which can cause errors.
Always ensure your source configuration matches exactly what you use in the source function.
sql
/* Wrong usage: using ref for raw source table */ select * from {{ ref('my_table') }} /* Correct usage: use source for raw tables */ select * from {{ source('my_source', 'my_table') }}
Quick Reference
| Function | Description | Example |
|---|---|---|
| source | References a raw table defined in sources.yml | {{ source('my_source', 'my_table') }} |
| ref | References a dbt model or seed | {{ ref('my_model') }} |
Key Takeaways
Use the source function to reference raw tables defined in your sources.yml file.
The source function takes two arguments: source name and table name.
Always define your sources correctly to avoid reference errors.
Use source for raw tables and ref for dbt models or seeds.
Check spelling carefully in both your source config and source function calls.