📘Introduction

In this hands-on dbt tutorial, you'll learn how to use pre-hooks to automate tasks such as creating backup tables before a model runs. Pre-hooks allow you to execute SQL before your dbt model builds, which is useful for auditing, data quality checks, or preparing the environment.

🎓 Preparing for dbt Analytics Engineering Certification?
Check out our exam study guide packed with practical examples and hands-on tutorials:

➡️📕 dbt Analytics Engineering Certification Guide

✅ Prerequisites

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

💡 What are pre-hooks in dbt?

pre-hook is SQL that runs automatically before a model executes.
They are commonly used for:

  • Backing up tables
  • Cleaning or truncating tables
  • Logging metadata or audit information
  • Enforcing data quality checks

In a dbt project pre-hooks can be defined:

  • Inside a model file using a config block.
  • Inside a seed or snapshot configuration YAML.
  • In dbt_project.yml for models, seeds, and snapshots.

🧠 Practical Example

Let’s walk through an example. Let's consider a dbt model called student that looks like this:

SELECT * FROM {{ ref("dim_student") }}

This simply selects all data from the dim_student table. In the warehouse, you can see that the table already exists.

🧙 Now, want to create a pre-hook that makes a backup of the table before the model runs.

⚙️1️⃣ Add pre-hook to your SQL code

Inside your model SQL file (models/student.sql), add a config block at the top:

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