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
UNIQUE
keyword.
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (field1, field2, ..., fieldN);
- Check the table's constraints using the
\d
command.
\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 CONSTRAINT
command.
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
- To rename a unique constraint, use the
RENAME CONSTRAINT
command.
ALTER TABLE table_name
RENAME CONSTRAINT old_constraint_name TO new_constraint_name;
- To disable a unique constraint, use the
SET CONSTRAINT
command.
ALTER TABLE table_name
SET CONSTRAINT constraint_name DEFERRED;
- To enable a unique constraint, use the
SET CONSTRAINT
command.
ALTER TABLE table_name
SET CONSTRAINT constraint_name IMMEDIATE;
Helpful links
More of Postgresql
- How can Zalando use PostgreSQL to improve its software development?
- How can I use PostgreSQL and ZFS snapshots together?
- How do I install and configure PostgreSQL on a Windows machine?
- How do I use PostgreSQL with Qt?
- How do I create a PostgreSQL function?
- How can I set a PostgreSQL interval to zero?
- How do I use PostgreSQL ZonedDateTime to store date and time information?
- How can I troubleshoot zero damaged pages in PostgreSQL?
- How can I use PostgreSQL with YAML?
- How do I use PostgreSQL and ZFS together?
See more codes...