What you will be able to do
- Tell which constraint types Snowflake enforces on standard tables and which it only records, and how hybrid tables differ
- Define single-column and composite primary keys with inline and out-of-line syntax
- Keep a non-enforced key unique during repeated loads
- Declare a child-to-parent foreign key, join along it, and find orphaned child rows with a LEFT JOIN
- Explain what RELY lets the optimizer do and what goes wrong when the data breaks a RELY constraint
Key concept
Declared vs enforced constraint — A declared constraint is stored with the table as metadata. An enforced constraint makes Snowflake reject writes that break it. On standard tables, PRIMARY KEY, UNIQUE and FOREIGN KEY are declared but never enforced; NOT NULL and CHECK are enforced.
1.Declared versus enforced constraints
A constraint is a rule attached to a table's columns: this column holds no nulls, these values are distinct, this column points at a key in another table. Snowflake supports the ANSI SQL constraint types, but on a standard table most of them are recorded and never checked. Whether a constraint is only declared or actually enforced decides what happens to a bad row: Snowflake either rejects it or loads it without a word.
| Constraint | What it guarantees | Standard table | Hybrid table |
|---|---|---|---|
| PRIMARY KEY | Distinct values, no NULLs; one per table | Optional, not enforced | Required, enforced |
| UNIQUE | Distinct values; NULLs allowed | Optional, not enforced | Optional, enforced |
| FOREIGN KEY | Values match a primary or unique key in another table or the same table | Optional, not enforced | Optional, enforced |
| NOT NULL | Column can't store NULL | Optional, enforced | Optional, enforced |
| CHECK | A SQL expression must hold for inserted or updated values | Optional, enforced | Optional, enforced; can be defined only at table creation |
Enforced means the engine refuses the write. Copy or insert a NULL into a NOT NULL column and the statement errors. CHECK constraints are always enforced too, which has a cost: a COPY INTO a table that has a CHECK constraint fails outright. A PRIMARY KEY, UNIQUE or FOREIGN KEY on a standard table is different. It is metadata. Snowflake stores it, returns it in GET_DDL, copies it when you clone the table, and never compares an incoming row against it.
This catches teams migrating from PostgreSQL or Oracle, where a primary key rejects a duplicate. Declare order_id NUMBER PRIMARY KEY on a standard Snowflake table and replay yesterday's file: the second copy of every order loads cleanly, and the report shows each order_id twice. How the key was written makes no difference. Inline or out-of-line, named or unnamed, with or without enforcement properties, a standard table's key is not checked by INSERT, COPY INTO or any other write. The constraint exists for data modeling, for compatibility with other databases, and for client tools. Tableau, for example, reads constraints to do join culling.
Hybrid tables are the exception. Every hybrid table must have a primary key, and Snowflake enforces it. Unique and foreign keys are enforced whenever you declare them, and you can't switch that off: marking a hybrid table's key NOT ENFORCED returns an invalid constraint property error. Foreign keys between hybrid tables also require both tables to be in the same database.
Checkpoint 1 of 9· Check yourself
A team creates a standard (permanent) Snowflake table with CONSTRAINT pk_orders PRIMARY KEY (order_id) declared out-of-line. A file that contains each order twice is then loaded with COPY INTO. What happens?
On standard tables, only NOT NULL and CHECK are enforced. PRIMARY KEY, UNIQUE and FOREIGN KEY are stored as metadata, whether they are declared inline or out-of-line, named or unnamed, so the duplicate rows load without error. Only a hybrid table would reject them.
“For standard tables, Snowflake supports defining and maintaining constraints, but doesn’t enforce them, except for NOT NULL and CHECK constraints, which are always enforced.”Source: docs.snowflake.com
Checkpoint 2 of 9· Exam question
An analyst migrates an orders table from PostgreSQL into a standard Snowflake table declared with order_id NUMBER PRIMARY KEY. A nightly reload from the source accidentally replays the same file, and the COPY INTO command finishes without errors. A report now shows the same order_id twice. What explains this behavior?
Correct answer: A — Snowflake records primary keys on standard tables as metadata only, so COPY INTO accepted the repeated order_id values and the duplicates now sit in the table.
- A. Correct: on standard tables Snowflake stores PRIMARY KEY, UNIQUE and FOREIGN KEY as informational metadata and enforces only NOT NULL, so the replayed rows load without any error.
- B. Incorrect:
ON_ERRORgoverns file parsing and data conversion errors, not key uniqueness. No load option makes a standard table reject duplicate keys. - C. Incorrect: inline and out-of-line declarations behave identically in Snowflake. Neither style enforces uniqueness on a standard table.
- D. Incorrect: clustering keys only influence micro-partition organization and have no connection to constraint enforcement.
2.Defining primary keys inline and out-of-line
You can declare a constraint when you create a table with CREATE TABLE, or add one later with ALTER TABLE, using either of two syntaxes. An inline constraint is part of a column's definition, so it can only cover that one column. An out-of-line constraint is a separate clause that lists its columns. It works for single-column keys, for keys on existing columns, and for multi-column keys, which have to be out-of-line. NOT NULL goes the other way: you can only write it inline.
CREATE TABLE table2 (
col1 INTEGER NOT NULL,
col2 INTEGER NOT NULL,
CONSTRAINT pkey_1 PRIMARY KEY (col1, col2) NOT ENFORCED
);The columns of a composite key are ordered. In pkey_1, col1 comes first and col2 second, and each has its own key sequence. That order matters later, because a foreign key must list the referenced columns in the same order. A primary key implies both NOT NULL and UNIQUE. A table can have only one primary key but several unique keys, and a UNIQUE column, unlike a primary key column, can contain NULLs.
ALTER TABLE table1
ADD COLUMN col3 VARCHAR NOT NULL CONSTRAINT uniq_col3 UNIQUE NOT ENFORCED;Give your constraints names. CONSTRAINT uniq_col3 makes the constraint easy to find and alter later. For an unnamed constraint, Snowflake generates a name, and GET_DDL leaves it out. GET_DDL also rebuilds every unique, primary and foreign key as an out-of-line clause, even if you declared it inline on one column. Inline and out-of-line are two ways of writing the same constraint. To add a key to a new table, your role needs CREATE TABLE on the schema. To add one to an existing table, it needs OWNERSHIP on the table.
Checkpoint 3 of 9· Fill the gap
table2 needs one key over both columns that identifies each row. By definition it must rule out NULLs in either column, and a child table will reference it. Which keyword completes this out-of-line constraint?
CREATE TABLE table2 (
col1 INTEGER NOT NULL,
col2 INTEGER NOT NULL,
CONSTRAINT pkey_1 ? KEY (col1, col2) NOT ENFORCED
);A PRIMARY KEY implies both NOT NULL and UNIQUE, and a table can have only one. A UNIQUE constraint still allows NULLs. This key covers two columns, so it has to be written out-of-line as it is here. The order (col1, col2) is the order a foreign key must use when it references it.
Source: docs.snowflake.com3.Keeping a non-enforced key unique during loads
On a standard table, nothing rejects a duplicate key, so keeping keys unique is the job of the pipeline that loads the table. The fixes that look like they turn enforcement on don't work, and seeing why is half the skill.
Of the key properties, NOT ENFORCED, DISABLE and NOVALIDATE are the defaults for primary and foreign keys. If you ask for ENFORCED, ENABLE or VALIDATE, you don't get a stricter key. You get no key at all. RELY is the one exception: specifying it still creates the constraint. But RELY tells the query optimizer to trust the key when it rewrites queries. It does not check incoming rows. The session parameter UNSUPPORTED_DDL_ACTION doesn't help either. It only decides whether those non-default property values raise an error. A table holds only one primary key anyway, so adding a second, stricter key isn't an option.
What works is to deduplicate in the load itself. Copy the files into a staging table first. Then run a MERGE into the target on order_id with only a WHEN NOT MATCHED THEN INSERT clause: keys that already exist in the target are skipped, and new keys are inserted. If you build the INSERT yourself, exclude keys already in the target and keep one row per key with QUALIFY, for example QUALIFY ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY loaded_at DESC) = 1. The staging copy needs deduplicating in the MERGE route too. If one file carries the same new key twice, both rows are unmatched and both get inserted. When several source rows match a single target row, MERGE results can also be nondeterministic.
Checkpoint 4 of 9· Check yourself
A nightly COPY INTO loads files into the standard table sales.orders, which declares order_id as its primary key. Someone sometimes replays an old file, and the duplicate rows have to stop. Which plan actually keeps order_id unique?
Snowflake never checks a primary key on a standard table. RELY only tells the optimizer to trust the key, UNSUPPORTED_DDL_ACTION only decides whether non-default properties raise an error, and inline syntax changes nothing. So the load itself has to deduplicate: clean up the staging copy, then insert only the keys that are new.
“If you decide to create a constraint that must be relied upon, ensure that your downstream processes can maintain data integrity.”Source: docs.snowflake.com
Checkpoint 5 of 9· Exam question
A data analyst loads daily order extracts into a standard Snowflake table sales.orders whose order_id primary key is not enforced. Replays of extract files must not create duplicate orders. Select TWO approaches that keep order_id unique without changing the table type.(Select 2)
Correct answers: A, B — Load the files into a staging table first, then run MERGE INTO sales.orders keyed on order_id with a WHEN NOT MATCHED THEN INSERT clause only.; Insert from staging using QUALIFY ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY loaded_at DESC) = 1 after excluding keys already present in the target.
- A. Correct: a MERGE that only inserts unmatched keys applies the uniqueness rule inside the load itself, so replayed rows find a match and are not inserted again.
- B. Correct: deduplicating the staged rows with ROW_NUMBER and filtering out keys already in the target guarantees that only one new row per
order_idis inserted. - C. Incorrect: Snowflake has no
ENFORCEDkeyword for standard-table key constraints, so this statement is not valid and would not add enforcement. - D. Incorrect:
RELYonly tells the optimizer it may trust the key for query rewrites. It never validates or rejects rows during a load. - E. Incorrect: no
CONSTRAINT_ENFORCEMENTsession parameter exists, and standard-table keys stay informational regardless of session settings.
4.Foreign keys and parent/child joins
A foreign key goes on the child table and names the parent's primary or unique key. Each child row says "I belong to that parent row." The referenced key can be in another table or in the same table, and the column types must match. Read the declaration below as a many-to-one link: many table3 rows can point at one table2 row, identified by (col1, col2).
CREATE TABLE table3 (
col_a INTEGER NOT NULL,
col_b INTEGER NOT NULL,
CONSTRAINT fkey_1 FOREIGN KEY (col_a, col_b) REFERENCES table2 (col1, col2) NOT ENFORCED
);The REFERENCES list must follow the parent key's column order. If pkey_1 is (col1, col2), then REFERENCES table2 (col2, col1) fails. You can leave out the referenced column names when the child and parent key columns have exactly the same names and data types. Creating the key takes two privileges: OWNERSHIP on the child table and REFERENCES on the parent, which is granted with GRANT REFERENCES ON TABLE <pk_table_name> TO ROLE <role_name>. Watch out when you copy tables. If you clone only the child, its new foreign key still points at the original parent.
The foreign key also tells you how to join the two tables: child column equals parent key. An inner join keeps only the child rows that found a parent (Join types: which rows survive). In the sample below, each employee row carries the project_id of its parent project.
SELECT p.project_ID, project_name, employee_ID, employee_name, e.project_ID
FROM projects AS p JOIN employees AS e
ON e.project_ID = p.project_ID
ORDER BY p.project_ID, e.employee_ID;NewEmployee, whose project_id is NULL. A NULL matches no project, and an inner join only keeps rows that have a match.
Snowflake doesn't enforce the foreign key on a standard table, so a child row can reference a parent that doesn't exist. To find those orphans, reverse the inner join: LEFT JOIN the child to the parent and keep the rows where the parent side came back NULL. For example: SELECT e.* FROM employees e LEFT JOIN projects p ON e.project_id = p.project_id WHERE p.project_id IS NULL. Add AND e.project_id IS NOT NULL to separate true orphans, which reference a missing project, from rows like NewEmployee, which reference no project at all. Running this check after every load is how you keep a declared foreign key true.
Checkpoint 6 of 9· Fill the gap
The parent table2 declares CONSTRAINT pkey_1 PRIMARY KEY (col1, col2). Which column name completes the child's foreign key so that the statement succeeds?
CREATE TABLE table3 (
col_a INTEGER NOT NULL,
col_b INTEGER NOT NULL,
CONSTRAINT fkey_1 FOREIGN KEY (col_a, col_b) REFERENCES table2 ( ? , col2) NOT ENFORCED
);The REFERENCES list names the parent's key columns, and it must follow the parent key's order, (col1, col2). Child column names such as col_a or col_b don't belong there. If the columns were listed in a different order, creating the foreign key would fail.
Source: docs.snowflake.comCheckpoint 7 of 9· Check yourself
employees declares a foreign key on project_id that references projects. Both are standard tables. After each load you want to list only the employee rows whose project_id points at a project that doesn't exist. Which query returns exactly those rows?
A foreign key on a standard table is not enforced, so orphan rows can load. A LEFT JOIN keeps child rows that have no match and fills the parent columns with NULL. The extra e.project_id IS NOT NULL filter leaves out rows like NewEmployee, which reference no project at all. An inner join drops unmatched rows, so the second query can never return any.
“The result of the inner join is augmented with a row for each row of o1 that has no matches in o2.”Source: docs.snowflake.com
5.RELY and join elimination
A primary key on a standard table isn't enforced, but it can still speed up queries if you vouch for the data. Take a dashboard query that LEFT JOINs fact_sales to dim_store on store_id and selects only fact_sales columns. If store_id is unique in dim_store, the join can't add or remove fact rows, so the join does nothing and could be skipped. The optimizer will only skip it if a constraint says the key is unique and the constraint is marked RELY.
RELY sets whether the optimizer takes a NOVALIDATE constraint into account when it rewrites queries. The default is NORELY, so declared keys are ignored. Set RELY on the primary key for the LEFT JOIN case above. For a parent/child pair, set it on both sides: ALTER TABLE table_with_primary_key ALTER CONSTRAINT a_primary_key_constraint RELY;, then the same on the child's foreign key. Clustering keys and other physical tuning don't unlock the rewrite. Only RELY does.
RELY is a promise that you have to keep. Snowflake still checks nothing on a standard table, so if the data breaks the constraint after you set RELY, query results can differ from what the same query returns under NORELY. In the store 42 case, a real join would match two dimension rows, while the eliminated join assumes there is only one. The damage can also spread: if a referential integrity violation exists under RELY, DML and CTAS statements may write incorrect data into other tables. Set RELY only on keys that a pipeline step, such as the deduplication and orphan checks above, keeps true.
Checkpoint 8 of 9· Fill the gap
store_id is unique in dim_store, and a pipeline step keeps it that way. You want the optimizer to skip the LEFT JOIN from fact_sales when a query selects only fact columns, so the existing key constraint is changed. Which property completes the statement?
ALTER TABLE table_with_primary_key ALTER CONSTRAINT a_primary_key_constraint ? ;RELY is the only property that makes the optimizer use a NOVALIDATE key when it rewrites queries, and so drop the join. ENFORCED, VALIDATE and ENABLE are non-default values on a standard table. Asking for one doesn't make the key stricter. It just means Snowflake doesn't create the constraint. Even with RELY, Snowflake checks nothing, so if duplicates get in, results can be wrong.
Source: docs.snowflake.comCheckpoint 9 of 9· Exam question
A BI dashboard joins fact_sales to dim_store with a LEFT JOIN on store_id but selects only columns from fact_sales. The analyst has verified that store_id is unique in dim_store and wants Snowflake to be able to skip the unnecessary join. Which action allows this optimization?
Correct answer: C — Declare a primary key on dim_store (store_id) with the RELY property so the optimizer may treat the column as unique and eliminate the join.
- A. Incorrect: clustering improves pruning but does not tell the optimizer that the join key is unique, so the join still runs.
- B. Incorrect: non-nullable fact columns alone do not prove that the dimension side has at most one match per row, which is what outer join elimination depends on.
- C. Correct: with
RELYon the dimension's primary key, the optimizer trusts the uniqueness metadata, sees that the left join cannot change the row count, and drops the join. - D. Incorrect: search optimization speeds selective lookups but has no bearing on whether a join can be removed from the plan.
Practise it for real
See for yourself which constraints a standard table enforces, and find an orphaned child row with a LEFT JOIN.
1.Create table2 and table3 exactly as in the composite primary key and foreign key samples.
Why: This gives you a parent with a declared primary key and a child with a declared foreign key.
You should see: Both tables are created with constraints pkey_1 and fkey_1.
2.Run INSERT INTO table2 VALUES (1, 1) twice.
Why: This tests whether the primary key rejects a duplicate.
You should see: Both inserts succeed, and table2 now holds two identical keys, because the primary key isn't enforced on a standard table.
3.Run INSERT INTO table3 VALUES (9, 9).
Why: No parent row (9, 9) exists, so this tests the foreign key.
You should see: The insert succeeds, because the foreign key isn't enforced either.
4.Run SELECT c.* FROM table3 c LEFT JOIN table2 p ON c.col_a = p.col1 AND c.col_b = p.col2 WHERE p.col1 IS NULL.
Why: This is the orphan check that takes the place of foreign key enforcement.
You should see: One row comes back: (9, 9).
5.Run INSERT INTO table2 VALUES (NULL, 2).
Why: col1 is declared NOT NULL, which is enforced.
You should see: The statement fails with an error.
Stuck? Get a nudge
If the duplicate insert in step 2 surprised you, re-read the table of which constraints each table type enforces.
Sources
(8)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“For standard tables, NOT NULL and CHECK are the only types of constraints that are enforced by Snowflake, regardless of this property.”
↩︎ Declared versus enforced constraints“Multi-column constraints (composite unique or primary keys) can only be defined out-of-line.”
↩︎ Defining primary keys inline and out-of-line“Specifying RELY does result in the creation of the new constraint.”
↩︎ Keeping a non-enforced key unique during loads“Snowflake provides a session parameter, UNSUPPORTED_DDL_ACTION, which determines whether specifying non-default values during constraint creation generates an error.”
↩︎ Keeping a non-enforced key unique during loads“the columns in the REFERENCES clause must be listed in the same order as they were listed for the primary key”
↩︎ Foreign keys and parent/child joins“You must use a role that has the REFERENCES privilege on the unique or primary key table.”
↩︎ Foreign keys and parent/child joins“Specifies whether a constraint in NOVALIDATE mode is taken into account during query rewrite.”
↩︎ RELY and join elimination“For related PRIMARY KEY and FOREIGN KEY constraints, set this property on both constraints.”
↩︎ RELY and join elimination“If the RELY property is set for a constraint and a violation of referential integrity occurs, DML and CTAS statements might insert incorrect data.”
↩︎ RELY and join elimination“For standard tables, NOT NULL and CHECK are the only types of constraints that are enforced by Snowflake, regardless of this property.”
↩︎ Key concept“For standard tables, NOT NULL and CHECK are the only types of constraints that are enforced by Snowflake, regardless of this property.”
↩︎ Exam trap 1“changing the defaults results in Snowflake not creating the constraint.”
↩︎ Exam trap 2“For standard tables, it is your responsibility to enforce RELY constraints”
↩︎ Exam trap 3“the columns in the REFERENCES clause must be listed in the same order as they were listed for the primary key”
↩︎ Exam trap 4“changing the defaults results in Snowflake not creating the constraint.”
↩︎ Prediction - 2.
“An attempt to copy or insert a NULL value into a NOT NULL column results in an error.”
↩︎ Declared versus enforced constraints“If you attempt to COPY INTO a table with CHECK constraints, the operation fails.”
↩︎ Declared versus enforced constraints“Inline constraints are created as part of the column definition and can only be used for single-column constraints.”
↩︎ Defining primary keys inline and out-of-line“A table can have multiple unique keys and foreign keys, but only one primary key.”
↩︎ Defining primary keys inline and out-of-line“A PRIMARY KEY constraint implies that the column is both NOT NULL and UNIQUE.”
↩︎ Defining primary keys inline and out-of-line“Table constraints, such as unique, primary, and foreign keys, are always reconstructed as out-of-line constraints, even if they consist of a single column.”
↩︎ Defining primary keys inline and out-of-line“All foreign keys must reference a corresponding primary or unique key that matches the column types of each column in the foreign key.”
↩︎ Foreign keys and parent/child joins - 3.
“Constraints on standard tables are provided primarily for data modeling purposes and compatibility with other databases”
↩︎ Declared versus enforced constraints“Primary key constraints are required and enforced on all hybrid tables, and other constraints are enforced when used.”
↩︎ Declared versus enforced constraints“For standard tables, Snowflake supports defining and maintaining constraints, but doesn’t enforce them, except for NOT NULL and CHECK constraints, which are always enforced.”
↩︎ Checkpoint“If you decide to create a constraint that must be relied upon, ensure that your downstream processes can maintain data integrity.”
↩︎ Checkpoint - 4.
“For standard tables, you are responsible for enforcing constraints on the data.”
↩︎ Keeping a non-enforced key unique during loads“These optimizations are performed only if you use the RELY constraint property”
↩︎ RELY and join elimination“If the integrity of your constraints is not maintained, the query results might differ if the RELY constraint property is set”
↩︎ RELY and join elimination - 5.
“When multiple rows in the source table match a single row in the target table, the results can be deterministic or nondeterministic.”
↩︎ Keeping a non-enforced key unique during loads - 6.
“In a SELECT statement, the QUALIFY clause filters the results of window functions.”
↩︎ Keeping a non-enforced key unique during loads - 7.
“If only the referencing table is copied, a new foreign key is created on the referencing table, which points to the original primary key table”
↩︎ Foreign keys and parent/child joins - 8.
“The result columns referencing o2 contain null.”
↩︎ Foreign keys and parent/child joins“The result of the inner join is augmented with a row for each row of o1 that has no matches in o2.”
↩︎ Checkpoint