2. Models & Materializations
Understanding Model Dependencies and Lineage
In dbt, the power of lineage is derived from the ref() function. This function abstracts away the underlying database schema and physical object names, replacing them with logical model references. By using {{ ref('model_name') }}, dbt automatically builds a Directed Acyclic Graph (DAG) that dictates the execution order, ensuring that downstream models only execute after their parent dependencies are successfully processed.
Using ref() is critical for environment portability. Because dbt manages the resolution of these references based on the configuration of your target environment, you can seamlessly transition from local development schemas to production schemas without altering a single line of SQL code. This approach enforces structural integrity, where a change in a column name at the staging level propagates naturally through the lineage chain, allowing dbt to detect potential breaking changes before they reach the production environment.
-- models/marts/fct_orders.sql -- The ref() function dynamically resolves the table name based on target config select order_id, customer_id, sum(amount) as total_revenue from {{ ref('stg_orders') }} group by 1, 2
Materialization Strategies
Materializations define the physical structure of a model in the database. Views are the default, offering low storage overhead and real-time data access, but they can be costly for complex analytical queries. Tables provide faster query performance but incur higher storage costs and require periodic refreshing. For transient logic that should never exist as a standalone table in the database, the ephemeral materialization provides a 'WITH' clause wrapper that is injected directly into dependent models during compilation.
Incremental models are the gold standard for high-volume datasets. By using an incremental strategy, dbt only processes the delta of new data since the last run. This is mathematically efficient, as the computational complexity $O(n)$ of a full refresh is reduced to $O(k)$ where $k$ is the number of rows inserted since the last execution. Implementing this requires defining a unique key and a predicate to filter for new data, typically using the is_incremental() macro.
{{ config(materialized='incremental', unique_key='event_id') }}
select * from {{ ref('raw_events') }}
{% if is_incremental() %}
where event_timestamp > (select max(event_timestamp) from {{ this }})
{% endif %}
Structuring Layers: Staging, Intermediate, and Marts
A mature dbt project architecture relies on modularity. Staging models (stg_) represent the 'clean room' layer, where we perform minimal transformations like renaming columns, casting data types, and handling nulls. These models typically map 1:1 to source tables. Intermediate models (int_) act as the bridge, performing complex joins, unioning, or window functions that prepare the data for final business consumption.
Finally, Mart models (fct_ or dim_) represent the refined, business-logic-heavy output. This separation of concerns allows data engineers to isolate bugs. If the issue is a data type mismatch, it is likely in staging. If it is a business logic error (e.g., how a revenue metric is calculated), the error is likely in the mart layer. Maintaining this clean hierarchy allows for high reusability of intermediate calculations, reducing redundancy across the entire project.
-- Example of a Staging transformation select id as order_id, cast(order_date as date) as order_date, coalesce(status, 'unknown') as status from {{ source('raw_data', 'orders') }}
Knowledge Check
Ready to test your understanding of 2. Models & Materializations?