postgresqlHow can I create a unique constraint in PostgreSQL?
To create a unique constraint in PostgreSQL, the following steps need to be taken:
- Create a table with the desired fields.
 
CREATE TABLE table_name (
    field1 data_type,
    field2 data_type,
    ...
    fieldN data_type
);
- Add a unique constraint to the table. This is done using the 
UNIQUEkeyword. 
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (field1, field2, ..., fieldN);
- Check the table's constraints using the 
\dcommand. 
\d table_name
Output example
                                   Table "public.table_name"
    Column     |           Type           | Collation | Nullable | Default
---------------+--------------------------+-----------+----------+---------
 field1        | character varying(100)   |           |          |
 field2        | integer                  |           |          |
 ...
 fieldN        | character varying(100)   |           |          |
Indexes:
    "constraint_name" UNIQUE CONSTRAINT, btree (field1, field2, ..., fieldN)
- To delete a unique constraint, use the 
DROP CONSTRAINTcommand. 
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
- To rename a unique constraint, use the 
RENAME CONSTRAINTcommand. 
ALTER TABLE table_name
RENAME CONSTRAINT old_constraint_name TO new_constraint_name;
- To disable a unique constraint, use the 
SET CONSTRAINTcommand. 
ALTER TABLE table_name
SET CONSTRAINT constraint_name DEFERRED;
- To enable a unique constraint, use the 
SET CONSTRAINTcommand. 
ALTER TABLE table_name
SET CONSTRAINT constraint_name IMMEDIATE;
Helpful links
More of Postgresql
- How can I set a PostgreSQL interval to zero?
 - How can I extract the year from a PostgreSQL timestamp?
 - How do I use PostgreSQL's XMIN and XMAX features?
 - How can I troubleshoot zero damaged pages in PostgreSQL?
 - How do I use PostgreSQL ZonedDateTime to store date and time information?
 - How can I use PostgreSQL with YAML?
 - How can I extract the year from a date in PostgreSQL?
 - How can I use PostgreSQL and ZFS snapshots together?
 - How do I use PostgreSQL's XMLTABLE to parse XML data?
 - How can I monitor PostgreSQL performance using Zabbix?
 
See more codes...