Skip to content

Latest commit

 

History

History
65 lines (43 loc) · 2.56 KB

add-constraint.md

File metadata and controls

65 lines (43 loc) · 2.56 KB
title summary toc
ADD CONSTRAINT
Use the ADD CONSTRAINT statement to add constraints to columns.
false

The ADD CONSTRAINT statement is part of ALTER TABLE and can add the following constraints to columns:

{{site.data.alerts.callout_info}} The Primary Key and Not Null constraints can only be applied through CREATE TABLE. The Default constraint is managed through ALTER COLUMN.{{site.data.alerts.end}}

Synopsis

{% include sql/diagrams/add_constraint.html %}

Required Privileges

The user must have the CREATE privilege on the table.

Parameters

Parameter Description
table_name The name of the table containing the column you want to constrain.
name The name of the constraint, which must be unique to its table and follow these identifier rules.
constraint_elem The Check, Foreign Keys, Unique constraint you want to add.

Adding/changing a Default constraint is done through ALTER COLUMN.

Adding/changing the table's Primary Key is not supported through ALTER TABLE; it can only be specified during table creation.

Examples

Add the Unique Constraint

Adding the Unique constraint requires that all of a column's values be distinct from one another (except for NULL values).

> ALTER TABLE orders ADD CONSTRAINT id_customer_unique UNIQUE (id, customer);

Add the Check Constraint

Adding the Check constraint requires that all of a column's values evaluate to TRUE for a Boolean expression.

> ALTER TABLE orders ADD CONSTRAINT total_0_check CHECK (total > 0);

Add the Foreign Key Constraint

Adding the Foreign Key constraint requires that all of a column's values are equal to an existing value in the column it references.

> ALTER TABLE orders ADD CONSTRAINT customer_fk FOREIGN KEY (customer) REFERENCEs customers (id);

See Also