Enforcing data integrity with YAML-defined constraints
dbt allows you to define data constraints (not null, primary key, foreign key, check, custom) directly in a model's YAML properties, which dbt then compiles into DDL statements enforced by the underlying data platform. This ensures data integrity guarantees are pushed down to the warehouse itself, not just validated in dbt tests, but support and enforcement behavior vary significantly by adapter.
1 · Learn the must-know
- Constraints are defined under the 'constraints' key at the model level (table-level constraints like
primary_key,foreign_key, check) or under a column's 'constraints' key (column-level constraints likenot_null,primary_key,foreign_key). - Constraints require the model to have a defined 'contract' (enforced: true) in its config, since dbt needs guaranteed column names, data types, and order to generate valid DDL.
- Platform enforcement differs: warehouses like Snowflake and Redshift may accept but not actively enforce
foreign_keyor check constraints (informational only), while Postgres and Databricks (via Delta) more strictly enforcenot_nulland check constraints. - For platforms that don't support ALTER-based constraint application post-load, dbt generates constraints inline as part of the CREATE TABLE statement, meaning the model build will fail at compile/run time if data violates a
not_nullor check constraint. - Primary key and foreign key constraints often require the 'type:
primary_key'/'type:foreign_key' syntax with a 'to' and 'field' reference for foreign keys, pointing to a ref() or source() relation. - Combining constraints with contracts turns schema and integrity violations into build-time errors rather than downstream surprises, but this also means any upstream schema drift will break the run until the YAML is updated to match.
2 · Check your understanding
A model declares a primary_key constraint on order_id with contract.enforced: true. On a Postgres target, dbt build fails immediately when duplicate order_id values exist. On a BigQuery target with the same YAML and the same duplicate data, the build succeeds without error. Why does the behavior differ between the two platforms?
What you have tried across dbt Analytics Engineering's objectives, not a readiness score.
Developing and optimizing dbt models45.16% of the exam*0 of 14 tried
Managing dbt models governance9.68% of the exam*0 of 3 tried
Debugging data modeling errors16.13% of the exam*0 of 5 tried
Troubleshooting and optimizing dbt pipelines6.45% of the exam*0 of 2 tried
Implementing dbt tests9.68% of the exam*0 of 3 tried
Implementing and maintaining external dependencies6.45% of the exam*0 of 2 tried
Leveraging the dbt state6.45% of the exam*0 of 2 tried
* Our estimate. dbt Labs publishes no section weights.
3 · Keep going
Ready for more? Take a weighted mock or try free practice questions.