📘 Introduction

In this hands-on dbt tutorial, you’ll learn how to use Jinja variables inside your dbt models to make your SQL code more dynamic, flexible, and reusable.

Instead of hardcoding values directly into your SQL logic, Jinja allows you to define variables that can be adjusted at runtime or reused across multiple models. This makes your transformations cleaner, easier to maintain, and adaptable to changing business requirements.

✅ Prerequisites

☑️ A dbt project set up
☑️ Set up Medallion Architecture
☑️ Source data loaded into your data warehouse
☑️ Source configurations defined in sources.yml

💡What is a Jinja variable in dbt?

Jinja is a templating language that dbt uses to make SQL models dynamic.

With Jinja, you can define variables, loops, and conditions — turning static SQL into flexible, parameterized logic. Instead of hardcoding constants or filter values, you can define a variable once and reuse it throughout your model or even override it at runtime.

🧠 Practical Example

Let’s walk through an example. In our dbt project, the table dim_course contains the following data:

We want to create a new dbt model that filters courses from the table dim_course based on their number of credits. The filter threshold should be flexible, allowing us to change it easily without rewriting SQL code — simply by modifying the value of the variable.

🗂️1️⃣ Create new .sql file inside the models/ folder

Inside your dbt project, navigate to the models/ folder and create a new SQL file named course_analytics.

✍️2️⃣ Set variable at the top of the model

At the top of your model file, define a variable using Jinja syntax:

{% set credits_threshold = 20 %}
CTA Image

If you’d like to dive deeper into dbt (data build tool), our book Building Modern Data Pipelines with dbt: From Raw Data to Gold Standard with the Medallion Architecture provides a hands-on guide to designing modern data pipelines. It covers dbt’s core concepts and best practices, including building Bronze, Silver, and Gold layers with the Medallion Architecture. It also serves as a hands-on study guide for the dbt Analytics Engineering Certification.

View on Amazon

⚙️3️⃣ Use variable within your SQL code

You can view this post with the tier: Academy Membership

Join academy now to read the post and get access to the full library of premium posts for academy members only.

Join Academy Already have an account? Sign In