Bird
Raised Fist0
dbtdata~10 mins

Built-in Jinja context variables in dbt - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Built-in Jinja context variables
Start dbt model rendering
↓
Load built-in Jinja context variables
↓
Use variables in Jinja template
↓
Render SQL with variable values
↓
Execute rendered SQL in database
↓
Return query results
dbt loads built-in Jinja context variables, uses them to render SQL templates, then runs the SQL to get results.
Execution Sample
dbt
{% set model_name = this.name %}
SELECT * FROM {{ ref('my_table') }}
WHERE model = '{{ model_name }}'
This code uses the built-in variable 'this.name' to get the current model's name and uses 'ref' to reference another model.
Execution Table
StepActionVariable/FunctionValue/ResultNotes
1Load built-in variable 'this'this.name'my_model'Current model name is 'my_model'
2Call function 'ref' with argument 'my_table'ref('my_table')'schema.my_table'Resolves to full table name
3Set variable 'model_name'model_name'my_model'Stores current model name
4Render SQL templateSQLSELECT * FROM schema.my_table WHERE model = 'my_model'Variables replaced with values
5Execute SQL in databaseQuery result[rows returned]Runs the rendered SQL
6EndExecution complete
💡 All built-in variables used and SQL rendered; query executed successfully.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
this.nameundefined'my_model''my_model''my_model'
model_nameundefinedundefined'my_model''my_model'
ref('my_table')undefinedundefinedundefined'schema.my_table'
Key Moments - 3 Insights
Why does 'this.name' have the value 'my_model'?
'this' is a built-in Jinja variable in dbt that represents the current model being rendered. In the execution_table step 1, 'this.name' is set to 'my_model', the model's name.
What does the 'ref' function do in the template?
'ref' is a built-in dbt function that returns the full database identifier for a referenced model or table. In step 2, 'ref('my_table')' resolves to 'schema.my_table'.
How are variables replaced in the SQL template?
In step 4, the Jinja template engine replaces variables like '{{ model_name }}' and '{{ ref('my_table') }}' with their actual values to produce executable SQL.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 1, what is the value of 'this.name'?
A'my_model'
B'my_table'
Cundefined
D'schema.my_table'
💡 Hint
Check the 'Value/Result' column in step 1 of the execution_table.
At which step does the SQL template get fully rendered with variable values?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look for the step where the 'SQL' variable shows the final query string.
If 'this.name' was 'sales_model' instead of 'my_model', how would the rendered SQL change at step 4?
AThe ref function would return a different table name.
BThe WHERE clause would use 'sales_model' instead of 'my_model'.
CThe SQL would not change.
DThe query would fail to execute.
💡 Hint
Check how 'model_name' is set from 'this.name' and used in the SQL in step 4.
Concept Snapshot
Built-in Jinja context variables in dbt provide info like current model (this.name).
Use {{ this.name }} or functions like {{ ref('model') }} inside templates.
Variables are replaced during rendering to produce executable SQL.
This helps write dynamic, reusable SQL models in dbt.
Full Transcript
In dbt, built-in Jinja context variables like 'this.name' give you info about the current model. The 'ref' function helps reference other models or tables. When dbt runs, it loads these variables, replaces them in your SQL templates, and then executes the final SQL. For example, 'this.name' might be 'my_model', and 'ref('my_table')' resolves to 'schema.my_table'. The template uses these to build the final query. This process lets you write flexible SQL that adapts to your project structure.

Practice

(1/5)
1. What does the built-in Jinja context variable run_started_at provide in dbt?
easy
A. The total number of models in the project
B. The name of the current model being executed
C. The timestamp when the current dbt run started
D. The database connection string

Solution

  1. Step 1: Understand the purpose of run_started_at

    This variable holds the timestamp marking the start of the dbt run.
  2. Step 2: Compare with other options

    Other options describe unrelated information like model name or connection details.
  3. Final Answer:

    The timestamp when the current dbt run started -> Option C
  4. Quick Check:

    run_started_at = Timestamp [OK]
Hint: Remember: run_started_at = run start time [OK]
Common Mistakes:
  • Confusing run_started_at with model name
  • Thinking it gives database info
  • Assuming it counts models
2. Which of the following is the correct syntax to access the current model name using a built-in Jinja context variable in dbt?
easy
A. {{ this.name }}
B. {{ model_name }}
C. {{ this.model }}
D. {{ current_model }}

Solution

  1. Step 1: Recall the correct variable for current model

    The variable this refers to the current model, and this.name gives its name.
  2. Step 2: Check syntax correctness

    Only {{ this.name }} correctly accesses the model name in Jinja syntax.
  3. Final Answer:

    {{ this.name }} -> Option A
  4. Quick Check:

    Current model name = {{ this.name }} [OK]
Hint: Use this.name for current model name [OK]
Common Mistakes:
  • Using undefined variables like model_name
  • Missing dot notation after this
  • Using incorrect variable names
3. Given the following dbt Jinja code snippet, what will be the output of {{ invocation_id }}?
{% set id = invocation_id %}{{ id }}
medium
A. The number of models executed so far
B. A unique identifier string for the current dbt run
C. The current timestamp
D. An error because invocation_id is undefined

Solution

  1. Step 1: Understand what invocation_id represents

    This variable holds a unique string ID for the current dbt run invocation.
  2. Step 2: Analyze the code snippet

    The code sets id to invocation_id and then outputs it, so it prints the unique run ID.
  3. Final Answer:

    A unique identifier string for the current dbt run -> Option B
  4. Quick Check:

    invocation_id = Unique run ID [OK]
Hint: invocation_id = unique run ID string [OK]
Common Mistakes:
  • Thinking it counts models
  • Confusing with timestamps
  • Assuming it causes an error
4. You wrote this dbt Jinja code but get an error:
{{ run_started_at.strftime('%Y-%m-%d') }}
. What is the likely cause?
medium
A. run_started_at is a string, not a datetime object, so strftime fails
B. Missing parentheses after run_started_at
C. strftime is not a valid method in Jinja
D. You must use single curly braces instead of double

Solution

  1. Step 1: Check the type of run_started_at

    In dbt, run_started_at is a string timestamp, not a datetime object.
  2. Step 2: Understand why strftime fails

    Since it's a string, calling strftime (a datetime method) causes an error.
  3. Final Answer:

    run_started_at is a string, not a datetime object, so strftime fails -> Option A
  4. Quick Check:

    String type blocks datetime methods [OK]
Hint: run_started_at is string; convert before datetime methods [OK]
Common Mistakes:
  • Assuming run_started_at is datetime
  • Using single braces for Jinja variables
  • Thinking strftime is unsupported in Jinja
5. You want to create a dbt model that adds a column with the current run's unique ID and the run start date in 'YYYY-MM-DD' format. Which Jinja code snippet correctly uses built-in context variables to achieve this?
hard
A. {% set run_date = run_started_at.split('-')[0] %} SELECT *, '{{ invocation_id }}' AS run_id, '{{ run_date }}' AS run_date FROM {{ this }}
B. {% set run_date = run_started_at.strftime('%Y-%m-%d') %} SELECT *, '{{ invocation_id }}' AS run_id, '{{ run_date }}' AS run_date FROM {{ this }}
C. SELECT *, '{{ invocation_id }}' AS run_id, '{{ run_started_at }}' AS run_date FROM {{ this }}
D. {% set run_date = run_started_at[:10] %} SELECT *, '{{ invocation_id }}' AS run_id, '{{ run_date }}' AS run_date FROM {{ this }}

Solution

  1. Step 1: Extract date from run_started_at string

    Since run_started_at is a string like 'YYYY-MM-DDTHH:MM:SS', slicing the first 10 characters gets the date.
  2. Step 2: Use invocation_id and run_date in SELECT

    The snippet correctly sets run_date and uses both variables in the SELECT statement.
  3. Step 3: Check other options for errors

    {% set run_date = run_started_at.strftime('%Y-%m-%d') %} SELECT *, '{{ invocation_id }}' AS run_id, '{{ run_date }}' AS run_date FROM {{ this }} tries to use strftime on a string (error). SELECT *, '{{ invocation_id }}' AS run_id, '{{ run_started_at }}' AS run_date FROM {{ this }} uses full timestamp, not formatted date. {% set run_date = run_started_at.split('-')[0] %} SELECT *, '{{ invocation_id }}' AS run_id, '{{ run_date }}' AS run_date FROM {{ this }} extracts only year incorrectly.
  4. Final Answer:

    Extracts date with run_started_at[:10] and uses invocation_id -> Option D
  5. Quick Check:

    Slice string for date, use invocation_id [OK]
Hint: Slice run_started_at[:10] for date, use invocation_id [OK]
Common Mistakes:
  • Using strftime on string variable
  • Not formatting run_started_at to date
  • Extracting only year instead of full date
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard