PostgreSQL UNIQUE Constraint
PostgreSQL UNIQUE Constraint
Summary: in this tutorial, you will learn about PostgreSQL UNIQUE constraint to make
sure that values stored in a column or a group of columns are unique across rows in a
table.
Sometimes, you want to ensure that values stored in a column or a group of columns are
unique across the whole table such as email address and username. PostgreSQL
provides you with the UNIQUE constraint to make sure that the uniqueness of the data is
maintained correctly.
With the UNIQUE constraint, every time you insert a new row, PostgreSQL checks if the
value is already in the table. If it finds that the new value is already there, it rejects the
change and issues an error. The same process is carried out for updating existing data.
When you add a UNIQUE constraint to a column or a group of columns, PostgreSQL will
create a unique index on the respective column or a group of columns automatically.
Note that the UNIQUE constraint above can be rewritten as a table constraint as shown
in the following query:
First, we insert a new row into the person table using INSERT statement:
The combination of values in column c2 and c3 will be unique across the whole table.
The value of the column c2 or c3 needs not to be unique.
Notice that the ALTER TABLE statement acquires an exclusive lock on the table. If you
have any pending transactions, it will wait for all transactions to complete before
changing the table. Therefore, you should check the pg_stat_activity table to see
the current pending transactions that are on-going using the following query:
1 SELECT
2 datid,
3 datname,
4 usename,
5 state
6 FROM
7 pg_stat_activity;
You should look at the result to find the state column with the value idle in
transaction. Those are the transactions that are pending to complete.
In this tutorial, we explained to you about the UNIQUE constraint to make values stored
in a column or a group of columns unique across the rows of a table.
Related Tutorials
PostgreSQL CREATE TABLE
PostgreSQL Primary Key
PostgreSQL Foreign Key
PostgreSQL CHECK Constraint
PostgreSQL Not-Null Constraint