0
0
DbtHow-ToBeginner ยท 3 min read

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.yml file.
  • 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.yml file.
  • Misspelling the source or table names in the source function call.
  • Using ref instead of source for 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

FunctionDescriptionExample
sourceReferences a raw table defined in sources.yml{{ source('my_source', 'my_table') }}
refReferences 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.