2: Managing dbt models governance

    Adding contracts to models

    A model contract is a build-time declaration that tells dbt the exact column names, ordered data types, and constraints the model promises to produce. When contract: {enforced: true} is set, dbt does two things before the warehouse touches a row. First, during dbt parse and dbt compile, it checks that every column declared in columns: has a data_type value, because the contract cannot be enforced without one. Second, at the start of the build for that model, dbt issues a no-op query that asks the warehouse to type-check the compiled SQL against the declared schema. If the model SQL drops a column, renames it, returns a different type, or returns columns in a different order than declared, the build fails before any data lands. Contracts are the only governance mechanism in dbt that prevent a destructive schema change from ever reaching the target relation.

    The problem a contract solves is the silent breaking change. Without a contract, an analytics engineer can rename customer_id to cust_id, cast revenue from numeric(18,2) to numeric(18,4), or remove a column, and the dbt run succeeds. Downstream consumers (other dbt models in the same project, BI tools, reverse ETL pipelines, exposures) then fail at query time, often hours later, often in production. A contract converts that runtime failure into a compile-time failure on the producer's pull request. The team that owns the model finds out before the team that consumes it does. That inversion is the whole point of model governance.

    Contracts are declared in the YAML properties file for the model, not in the SQL file itself. The minimal shape looks like this:

    # models/marts/dim_customers.yml
    version: 2
    
    models:
     - name: dim_customers
     config:
     contract: {enforced: true}
     columns:
     - name: customer_id
     data_type: integer
     constraints:
     - type: not_null
     - type: primary_key
     - name: customer_email
     data_type: varchar
     constraints:
     - type: not_null
     - name: lifetime_value
     data_type: numeric(18,2)
     - name: signup_date
     data_type: date
    

    Two details in that snippet matter for the exam. The order of entries under columns: is the order dbt requires the model SQL to return them, and the names must match exactly. If dim_customers.sql selects customer_email before customer_id, the contract fails parse. Add a comment to the model SQL reminding future maintainers that the SELECT list is contract-ordered; many teams keep an explicit SELECT customer_id, customer_email, lifetime_value, signup_date FROM ... at the bottom of the file rather than relying on SELECT * from an upstream CTE.

    -- models/marts/dim_customers.sql
    {{ config(materialized='table') }}
    
    WITH base AS (
     SELECT
     customer_id,
     customer_email,
     sum(order_total) AS lifetime_value,
     min(order_date) AS signup_date
     FROM {{ ref('stg_orders') }}
     GROUP BY 1, 2
    )
    
    SELECT
     customer_id,
     customer_email,
     lifetime_value,
     signup_date
    FROM base
    

    Column data types and warehouse normalization

    The data_type: value is matched against the warehouse's view of the column after compilation. Adapters normalize names differently. On Snowflake, int, integer, and number(38,0) all resolve to NUMBER(38,0) when the warehouse reports the table back, so declaring data_type: number(38,0) is the safe form there. On BigQuery, declare int64 rather than integer. On Databricks, declare bigint. The adapter doc page for the model's target lists the canonical form. A contract that uses the wrong synonym fails the type check even when the values would otherwise round-trip cleanly, because the comparison is string-equal after normalization.

    💡 Exam Trap: Contracts compare normalized type strings, not type families. numeric(18,2) declared in YAML does NOT match a column the warehouse reports as numeric(18,4). A common build failure is declaring numeric (no precision) and the warehouse returning numeric(38,0). Always use the precision the warehouse will report, never the loose alias.

    Constraints: what dbt enforces vs what the warehouse enforces

    Constraints under columns: are a separate concept from data_type:. dbt supports five constraint types in the YAML schema: not_null, primary_key, foreign_key, unique, and check. Whether each one is enforced at write time depends on the adapter. Snowflake informational constraints (everything except not_null) are accepted by the warehouse and recorded in INFORMATION_SCHEMA but are not enforced on INSERT. BigQuery does not enforce primary_key or foreign_key either, but it does enforce not_null. Postgres and SQL Server enforce all five. Databricks Unity Catalog enforces not_null and check constraints on Delta tables; primary_key, foreign_key, and unique are informational. The exam tests this distinction by giving a Snowflake model with a unique constraint and asking whether duplicate rows would cause the build to fail. The answer is no for Snowflake; yes for Postgres.

    Constraints can also be declared at the model level rather than the column level, which is the only way to express composite keys:

    models:
     - name: fct_orders
     config:
     contract: {enforced: true}
     constraints:
     - type: primary_key
     columns: [order_id, order_line_id]
     - type: foreign_key
     columns: [customer_id]
     expression: analytics.dim_customers (customer_id)
     - type: check
     expression: "order_total >= 0"
     name: order_total_non_negative
     columns:
     - name: order_id
     data_type: integer
     - name: order_line_id
     data_type: integer
     - name: customer_id
     data_type: integer
     - name: order_total
     data_type: numeric(18,2)
    

    The expression: key under a foreign_key constraint takes the fully-qualified parent table reference and the parent column in parentheses. The check constraint takes raw SQL and must reference columns by their unqualified names. Named constraints (the optional name: key) make warehouse error messages traceable back to the YAML.

    📊 Limit: dbt enforces not_null and check constraints by emitting them as DDL clauses where the adapter supports them. The other three constraint types behave as documentation on adapters that do not enforce them. For row-level guarantees on those adapters, add a dbt unique test alongside the constraint declaration. The contract gives you SHAPE enforcement; tests give you VALUE enforcement.

    Contracts and the build flow

    When dbt build (or dbt run) processes a contracted model, the order of operations is: parse YAML, compile model SQL, issue a CREATE OR REPLACE TABLE ... AS SELECT * FROM (model_sql) WHERE 1=0 style probe to fetch the column list and types the SQL would produce, compare that to the declared contract, then either fail with a structured error or proceed with the real build. The probe runs against the warehouse, so contract enforcement does consume warehouse compute, though only at metadata cost (no rows scanned).

    ⚠️ Anti-Pattern: Declaring a contract on an ephemeral or view model that is owned by a single team and has no external consumers. Contracts add review burden every time the producer wants to add a column (the YAML must be updated in the same PR), and the benefit (preventing breaking changes to consumers) does not apply when there are no consumers. Reserve enforced contracts for public models, models referenced by exposures, and mart-layer tables that BI tools query directly.

    Constraint inheritance is not a thing

    A common misconception is that adding a contract to a base model causes downstream models built from it to inherit the constraints. dbt does not propagate contracts down the DAG. Every model that needs a contract must declare its own. This is by design: the schema your model produces is its own promise, not its upstream's.

    💡 Exam Trap: A question shows stg_customers with contract: {enforced: true} and customer_id declared as not_null. It then shows dim_customers (which selects from stg_customers) without a contract. Asked whether dim_customers.customer_id is guaranteed non-null, the answer is no. Without an enforced contract on dim_customers itself, dbt makes no promise about its output. Downstream consumers must contract every layer they care about.

    Decision Anchor: when to contract

    Choose contract: {enforced: true} when the model is consumed by anything outside the producing team's full control (BI dashboards, exposures, external dbt projects, reverse ETL syncs, downstream APIs). Choose to leave the model uncontracted when it is a staging or intermediate model whose only consumers are other models in the same project that will be re-tested on every build anyway. The cost is YAML maintenance overhead on every column change; the benefit is converting silent runtime breakage into loud compile-time breakage.

    Diagram: contract enforcement flow

    Two further behaviors are worth pinning down before moving on. First, a contracted model can still be incremental. The contract checks the SHAPE of the SELECT, not the merge strategy. You can declare materialized: incremental, unique_key: order_id, and contract: {enforced: true} on the same model; the merge MERGE INTO target picks up the contracted column types automatically. Second, contracts work with Python models as well as SQL models, but the Python model must return a DataFrame whose columns match the YAML declaration exactly. Snowpark, PySpark, and pandas-on-Spark all expose column-order and column-type APIs; the contract check is identical regardless of language.

    🎯 Scenario: A finance team owns fct_revenue, which a Looker dashboard reads. An analytics engineer adds a tax_amount column to the SELECT but forgets to update the YAML. With a contract enforced, the next dbt build fails with Compilation Error: Contract for model fct_revenue has columns [order_id, gross_amount] but model produced [order_id, gross_amount, tax_amount]. The PR cannot merge until the YAML is updated, the change is reviewed, and the dashboard owner is notified. Without a contract, the build succeeds, the column is published, and the dashboard's SELECT * query starts returning an extra column that breaks a Looker LookML field definition the following morning.

    The exam emphasizes three things about contracts: every column needs a data_type, constraint enforcement depends on the warehouse adapter, and contracts catch SHAPE drift at build time, not VALUE drift at row time. Tie those three points to the YAML you write and the exam questions on contracts become mechanical reads.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the dbt - Analytics Engineering Certification learning hub.