ADD PRIMARY KEY creates a unique, non-null column or column set and enforces referential integrity in Snowflake tables.
PRIMARY KEY constraints guarantee that each row has a unique, non-null identifier. They improve data quality, simplify joins, and help other teams understand table intent, even though Snowflake does not physically enforce uniqueness.
Add a PRIMARY KEY clause directly after the column list. This is ideal when defining a new dimension or fact table.
CREATE TABLE Customers (
id NUMBER NOT NULL,
name STRING,
email STRING,
created_at TIMESTAMP,
PRIMARY KEY (id)
);
Use ALTER TABLE ADD PRIMARY KEY. Confirm the data is unique before running the command to avoid silent data issues.
ALTER TABLE Orders
ADD CONSTRAINT pk_orders PRIMARY KEY (id);
Yes—list multiple columns inside the parentheses. Composite keys are common on bridge tables such as OrderItems (order_id, product_id).
ALTER TABLE OrderItems
ADD CONSTRAINT pk_orderitems PRIMARY KEY (order_id, product_id);
First drop the existing constraint, then add the new one. This pattern is useful when switching from a surrogate to a natural key.
ALTER TABLE Products DROP CONSTRAINT pk_products;
ALTER TABLE Products
ADD CONSTRAINT pk_products_new PRIMARY KEY (name);
1) Name constraints consistently with a pk_
prefix. 2) Validate uniqueness before applying. 3) Document intent in column comments. 4) Use surrogate keys (NUMBER, SEQUENCE) for large fact tables to keep joins fast.
• Enforce unique customer IDs.
• Prevent duplicate order lines.
• Support referential constraints when loading data into BI tools.
Snowflake stores PRIMARY KEY metadata but does not block duplicate inserts. Pair the constraint with upstream data checks or periodic deduplication queries.
No. The platform stores the constraint as metadata only. Use ETL checks or streams/tasks to enforce uniqueness.
Yes, but avoid it. Rows with NULL values break the guarantee of a non-null identifier. Clean the data before adding the key.
Query INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_type = 'PRIMARY KEY'.