postgresql_16:3.2.4.3 Unique Constraints
PostgreSQL 16 > The SQL Language > Data Definition > Constraints > Unique Constraints
Unique constraints ensure that the data contained in a column, or a group of columns, is unique among all the rows in the table. The syntax is: CREATE TABLE products ( product_no integer *UNIQUE*, name text, price numeric ); when written as a column constraint, and: CREATE TABLE products ( product_no integer, name text, price numeric, *UNIQUE (product_no)* ); when written as a table constraint.
To define a unique constraint for a group of columns, write it as a table constraint with the column names separated by commas: CREATE TABLE example ( a integer, b integer, c integer, *UNIQUE (a, c)* ); This specifies that the combination of values in the indicated columns is unique across the whole table, though any one of the columns need not be (and ordinarily isn't) unique.
You can assign your own name for a unique constraint, in the usual way: CREATE TABLE products ( product_no integer *CONSTRAINT must_be_different* UNIQUE, name text, price numeric );
Adding a unique constraint will automatically create a unique B-tree index on the column or group of columns listed in the constraint. A uniqueness restriction covering only some rows cannot be written as a unique constraint, but it is possible to enforce such a restriction by creating a unique partial index (see postgresql_16:3.8.8).
In general, a unique constraint is violated if there is more than one row in the table where the values of all of the columns included in the constraint are equal. By default, two null values are not considered equal in this comparison. That means even in the presence of a unique constraint it is possible to store duplicate rows that contain a null value in at least one of the constrained columns. This behavior can be changed by adding the clause NULLS NOT DISTINCT, like CREATE TABLE products ( product_no integer UNIQUE *NULLS NOT DISTINCT*, name text, price numeric ); or CREATE TABLE products ( product_no integer, name text, price numeric, UNIQUE *NULLS NOT DISTINCT* (product_no) ); The default behavior can be specified explicitly using NULLS DISTINCT. The default null treatment in unique constraints is implementation-defined according to the SQL standard, and other implementations have a different behavior. So be careful when developing applications that are intended to be portable.