4.3 Relational Constraints & Query Optimizer Integration
Key Takeaways
- On standard Snowflake tables only NOT NULL and CHECK constraints are enforced; PRIMARY KEY, UNIQUE, and FOREIGN KEY are informational, while hybrid tables enforce primary, unique, and foreign keys.
- Constraint property defaults are NOT ENFORCED, DISABLE, NOVALIDATE (VALIDATE for CHECK), and NORELY; on standard tables, changing a default other than RELY means Snowflake does not create the constraint.
- Setting RELY on related PRIMARY KEY/UNIQUE and FOREIGN KEY constraints (ALTER TABLE ... ALTER CONSTRAINT ... RELY) lets the optimizer eliminate unnecessary joins.
- Misconfiguring `RELY` on unenforced constraints with unvalidated or duplicate data causes silent query corruption, returning inaccurate row counts or missing filter logic without errors.
- Upstream data pipelines (such as dbt tests or ETL staging assertions) must strictly enforce referential integrity and uniqueness before `RELY` is enabled on production tables.
4.3 Relational Constraints & Query Optimizer Integration
In traditional relational database management systems (RDBMS) like Oracle, SQL Server, or PostgreSQL, constraints serve two concurrent purposes: they strictly enforce data integrity at write time (rejecting invalid inserts) and they provide structural metadata to the query optimizer. In Snowflake, however, constraint architecture is fundamentally decoupled from write-time validation.
For the SnowPro Advanced: Architect exam, you must master the critical distinction between enforced and informative (declarative) constraints, understand the ENABLE, VALIDATE, and RELY constraint properties, how RELY empowers the optimizer to execute Join Elimination, and recognize the catastrophic risks of silent data corruption when constraints are misused.
Relational Constraints in Snowflake: Enforced vs. Declarative Realities
Snowflake supports standard ANSI SQL constraint declarations, but their enforcement behavior differs radically from traditional transactional databases:
-- Creating a table with primary, unique, foreign key, and not null constraints
CREATE TABLE sales_dw.marts.dim_customer (
customer_key NUMBER(38,0) NOT NULL,
customer_id VARCHAR(64) NOT NULL,
email VARCHAR(255),
registration_date DATE,
CONSTRAINT pk_customer PRIMARY KEY (customer_key),
CONSTRAINT uq_customer_id UNIQUE (customer_id)
);
CREATE TABLE sales_dw.marts.fact_sales (
sale_id NUMBER(38,0) NOT NULL,
customer_key NUMBER(38,0) NOT NULL,
amount NUMBER(12,2) NOT NULL,
CONSTRAINT pk_sales PRIMARY KEY (sale_id),
CONSTRAINT fk_sales_customer FOREIGN KEY (customer_key)
REFERENCES sales_dw.marts.dim_customer (customer_key)
);
The Core Enforcement Rule
| Constraint Type | Standard Columnar Tables | Hybrid Tables (Unistore) | Write-Time Enforcement Behavior |
|---|---|---|---|
NOT NULL | ENFORCED | ENFORCED | Snowflake rejects any INSERT, UPDATE, or COPY that attempts to assign a NULL value to the column. |
CHECK | ENFORCED | ENFORCED | Rows that violate the check expression are rejected (defaults to VALIDATE). |
PRIMARY KEY | NOT ENFORCED | ENFORCED | Declarative metadata only. Snowflake permits duplicate keys and NULL values (unless NOT NULL is explicitly added). |
UNIQUE | NOT ENFORCED | ENFORCED | Declarative metadata only. Snowflake permits duplicate non-null values. |
FOREIGN KEY | NOT ENFORCED | ENFORCED | Declarative metadata only. Snowflake does not verify that referenced keys exist in the parent table. |
Architectural Note: Snowflake's primary analytical tables are designed for high-concurrency, petabyte-scale distributed ingestion. Enforcing unique or foreign key constraints at insert time across hundreds of compute nodes would require global distributed row locking and continuous network coordination, severely throttling write throughput. Consequently, Snowflake makes primary, unique, and foreign keys informative rather than enforced on standard tables; only
NOT NULLandCHECKare enforced.
The ENABLE, VALIDATE, and RELY Constraint Properties
Snowflake accepts the Oracle-style properties ENABLE | DISABLE, VALIDATE | NOVALIDATE, and RELY | NORELY (listed in the blueprint as ENABLE/RELY/VALIDATE). On standard tables these properties exist mainly to ease migrations: they are not enforced or maintained, and changing any default other than RELY causes Snowflake not to create the constraint.
| Property | Default | Meaning on standard tables |
|---|---|---|
ENFORCED / NOT ENFORCED | NOT ENFORCED | PK/UK/FK are never enforced; NOT NULL and CHECK always are |
ENABLE / DISABLE | DISABLE | Compatibility with Oracle only |
VALIDATE / NOVALIDATE | NOVALIDATE for PK/FK (VALIDATE for CHECK) | Whether existing rows are checked when the constraint is created |
RELY / NORELY | NORELY | Whether the optimizer may trust the constraint for query rewrites |
The only property you normally change on standard tables is RELY:
ALTER TABLE sales_dw.marts.dim_customer
ADD CONSTRAINT pk_customer PRIMARY KEY (customer_key) RELY;
ALTER TABLE sales_dw.marts.fact_sales
ADD CONSTRAINT fk_sales_customer FOREIGN KEY (customer_key)
REFERENCES sales_dw.marts.dim_customer (customer_key) RELY;
1. NOVALIDATE vs. VALIDATE
- Default Behavior: Primary and foreign keys default to
NOVALIDATE— Snowflake does not scan existing rows to prove the constraint holds. - On standard tables, requesting
VALIDATE(a non-default value) means the constraint is not created, because Snowflake does not maintain that property. - On hybrid tables, adding a UNIQUE or FOREIGN KEY constraint always validates existing rows, regardless of this property.
2. NORELY vs. RELY (The Optimizer Switch)
| Property | Meaning to the Cost-Based Optimizer (CBO) | Default Setting |
|---|---|---|
NORELY | The optimizer assumes the constraint cannot be trusted for query rewrites because data integrity is unverified. Constraints with NORELY serve purely as documentation and BI tool schema introspection. | Default for all declarative constraints. |
RELY | The data architect explicitly asserts that upstream data pipelines guarantee 100% data integrity (uniqueness, referential integrity). The optimizer is instructed to rely on the constraint to perform aggressive query optimizations, including Join Elimination. | Must be explicitly enabled via DDL. |
-- Modifying existing constraints to enable RELY (set it on both related keys)
ALTER TABLE sales_dw.marts.dim_customer ALTER CONSTRAINT pk_customer RELY;
ALTER TABLE sales_dw.marts.fact_sales ALTER CONSTRAINT fk_sales_customer RELY;
-- Inspecting constraint properties and RELY status
SHOW PRIMARY KEYS IN TABLE sales_dw.marts.dim_customer;
-- Output column 'rely' indicates 'true' or 'false'
Cost-Based Optimizer Integration & Join Elimination Mechanics
Modern Business Intelligence (BI) tools (e.g., Tableau, Looker, Power BI) frequently generate automated SQL queries that join a central fact table to 10 or 15 dimension tables. Often, a specific dashboard widget or report projects columns from only the fact table and one or two dimensions, leaving several joined dimension tables completely unreferenced in the SELECT list and WHERE clauses.
The Join Elimination Optimization
Consider the following analytical query:
SELECT
f.order_date,
SUM(f.sales_amount) AS daily_revenue
FROM sales_dw.marts.fact_sales f
LEFT JOIN sales_dw.marts.dim_customer c
ON f.customer_key = c.customer_key
GROUP BY f.order_date;
Notice that the query joins dim_customer, but zero columns from dim_customer are projected in the SELECT list or filtered in a WHERE clause.
What Happens Under NORELY (Default):
- The optimizer does not know whether
customer_keyindim_customeris unique. - If
dim_customercontains duplicatecustomer_keyvalues, theLEFT JOINwould duplicate rows fromfact_sales(a cartesian fan-out), altering the sum ofsales_amount. - Because the optimizer cannot guarantee that
dim_customeris unique, it must physically execute the join. It scansdim_customer, builds a hash table in memory, and scansfact_sales, burning unnecessary virtual warehouse credits and compute time.
What Happens Under RELY:
- The architect has marked both
pk_customerandfk_sales_customerwithRELY. - The optimizer verifies that:
dim_customer.customer_keyis unique (guaranteed byRELYon the Primary Key).- Every row in
fact_salesjoins to at most one row indim_customer. - No columns from
dim_customerare required in the output.
- The optimizer performs Join Elimination: it completely excises
dim_customerfrom the physical execution plan! - In the Snowflake Query Profile, the table scan for
dim_customer, the hash table build operator, and the join operator completely disappear. The query runs as a simple, lightning-fast scan againstfact_salesalone.
Production Governance, Silent Data Corruption Risks, and Exam Traps
While RELY delivers immense performance benefits for enterprise BI queries, it introduces the most dangerous trap in Snowflake data architecture: silent data corruption.
The Catastrophic Risk of Erroneous RELY Configurations
If an architect enables RELY on a table where the upstream ETL/ELT pipeline fails to enforce referential integrity or uniqueness, the optimizer will rewrite queries under false assumptions, producing mathematically incorrect results without throwing any error.
Failure Scenario 1: Orphan Fact Records (Referential Integrity Violation)
Suppose fact_sales contains rows where customer_key = 9999, but key 9999 does not exist in dim_customer. Both tables have constraints configured with RELY.
- Query A (Join Eliminated):
Because no columns fromSELECT SUM(f.sales_amount) FROM fact_sales f JOIN dim_customer c ON f.customer_key = c.customer_key;care queried, the optimizer eliminates theJOIN. It calculates the sum across all fact rows, including the orphan rows withcustomer_key = 9999. Revenue reported: $10,000,000. - Query B (Join Forced):
BecauseSELECT c.region, SUM(f.sales_amount) FROM fact_sales f JOIN dim_customer c ON f.customer_key = c.customer_key GROUP BY c.region;c.regionis selected, the optimizer cannot eliminate the join. TheINNER JOINexecutes physically and filters out the orphan rows. Total revenue summed across all regions: $9,500,000. - The Disaster: Two queries that should logically calculate the same total return contradictory figures! Neither query errored out, leading to silent executive reporting discrepancies.
Failure Scenario 2: Duplicate Keys in Dimension (Uniqueness Violation)
If duplicate customer keys exist in dim_customer, Query A (join eliminated) returns unmultiplied sums, while Query B (join executed) multiplies rows, producing severe data inflation.
Architectural Best Practices for Constraints
- Enforce Upstream First: Never set
RELYon Snowflake tables unless upstream data pipelines (e.g., dbt tests, automated staging validation, or Great Expectations) strictly assert primary key uniqueness and foreign key integrity before publishing data to production tables. - Emergency Mitigation: If an integrity violation is detected in production, immediately downgrade constraints to
NORELYto force physical joins until the data is remediated:ALTER TABLE sales_dw.marts.dim_customer ALTER CONSTRAINT pk_customer NORELY; - Third-Party Tool Metadata: Informative constraints (even with
NORELY) are invaluable for data modeling tools, data catalogs (e.g., Alation, Collibra), and BI semantic layers (e.g., Looker LookML, Power BI DirectQuery) to infer correct relationship topologies automatically.
A data architect defines a PRIMARY KEY and FOREIGN KEY relationship between a fact table and a dimension table in Snowflake. What is the enforcement behavior of these constraints during standard batch COPY INTO or INSERT operations on standard columnar tables?
An architect is troubleshooting a dashboard query that joins a 5-billion-row fact table to a product dimension table. The query aggregates only fact table metrics and does not project or filter on any dimension columns. Despite this, the Query Profile reveals that the dimension table was scanned and an in-memory hash join was executed. What configuration is required to enable Join Elimination for this query?
What is the primary operational risk of enabling the RELY property on a FOREIGN KEY constraint in Snowflake when upstream ETL pipelines fail to maintain referential integrity?