258

As I can understand documentation the following definitions are equivalent:

create table foo (
    id serial primary key,
    code integer,
    label text,
    constraint foo_uq unique (code, label));

create table foo (
    id serial primary key,
    code integer,
    label text);
create unique index foo_idx on foo using btree (code, label);    

However, a note in the manual for Postgres 9.4 says:

The preferred way to add a unique constraint to a table is ALTER TABLE ... ADD CONSTRAINT. The use of indexes to enforce unique constraints could be considered an implementation detail that should not be accessed directly.

(Edit: this note was removed from the manual with Postgres 9.5.)

Is it only a matter of good style? What are practical consequences of choice one of these variants (e.g. in performance)?

klin
  • 112,967
  • 15
  • 204
  • 232
Adam Piotrowski
  • 2,945
  • 3
  • 20
  • 23
  • 34
    The (only) practical difference is that you can create a foreign key to a unique constraint but not to a unique index. –  May 08 '14 at 13:13
  • 36
    An advantage the other way around ([as came up in another question recently](http://stackoverflow.com/a/23449309/157957)) is that you can have a *partial* unique index, such as "Unique ( foo ) Where bar Is Null". AFAIK, there's no way to do that with a constraint. – IMSoP May 08 '14 at 13:21
  • 4
    @a_horse_with_no_name I'm not sure when this happened, but this no longer appears to be true. This SQL fiddle allows foreign key references to a unique index: http://sqlfiddle.com/#!17/20ee9; EDIT: adding a 'filter' to the unique index causes this to stop working (as expected) – user1935361 Jan 26 '18 at 16:01
  • 4
    from postgres documentation: PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. https://www.postgresql.org/docs/9.4/static/indexes-unique.html – maggu May 26 '18 at 02:36
  • I concur with @user1935361, if it were not possible to create a foreign key to a unique index (with PG 10 at least) I would have run into this issue a long time ago. – Andy Jun 26 '18 at 14:21
  • [postgres mailing list answer](https://www.postgresql.org/message-id/CAO8h7BJMX5V1TqzScTx2Nr1jH5iUFG8A071y-g1b_kdzpu9PDw%40mail.gmail.com) – Eugen Konkov Jul 11 '18 at 18:08
  • @a_horse_with_no_name: I was under the same impression (fk requires unique *constraint*), but that seems to have been a misunderstanding all along. See: https://stackoverflow.com/q/61249732/939860 – Erwin Brandstetter Apr 17 '20 at 02:15
  • @a_horse_with_no_name: Another difference is that [you cannot use the `ON CONFLICT ON CONSTRAINT` clause with unique indexes](https://stackoverflow.com/a/62322630/521799) – Lukas Eder Jun 11 '20 at 10:49
  • 2
    one of the differences is deferrable behavior - constraints support it, indexes don't https://www.postgresql.org/docs/current/sql-set-constraints.html – Nikolai Jan 24 '21 at 16:46
  • @maggu Yes, when I add 'id serial primary key' to my CREATE TABLE... DDL, it looks like postgresql automatically adds a CREATE UNIQUE INDEX source DDL – ennth Oct 10 '21 at 22:36
  • @nameless_horse what do you mean with your poor comment? – Jack Apr 08 '22 at 09:17

10 Answers10

211

I had some doubts about this basic but important issue, so I decided to learn by example.

Let's create test table master with two columns, con_id with unique constraint and ind_id indexed by unique index.

create table master (
    con_id integer unique,
    ind_id integer
);
create unique index master_unique_idx on master (ind_id);

    Table "public.master"
 Column |  Type   | Modifiers
--------+---------+-----------
 con_id | integer |
 ind_id | integer |
Indexes:
    "master_con_id_key" UNIQUE CONSTRAINT, btree (con_id)
    "master_unique_idx" UNIQUE, btree (ind_id)

In table description (\d in psql) you can tell unique constraint from unique index.

Uniqueness

Let's check uniqueness, just in case.

test=# insert into master values (0, 0);
INSERT 0 1
test=# insert into master values (0, 1);
ERROR:  duplicate key value violates unique constraint "master_con_id_key"
DETAIL:  Key (con_id)=(0) already exists.
test=# insert into master values (1, 0);
ERROR:  duplicate key value violates unique constraint "master_unique_idx"
DETAIL:  Key (ind_id)=(0) already exists.
test=#

It works as expected!

Foreign keys

Now we'll define detail table with two foreign keys referencing to our two columns in master.

create table detail (
    con_id integer,
    ind_id integer,
    constraint detail_fk1 foreign key (con_id) references master(con_id),
    constraint detail_fk2 foreign key (ind_id) references master(ind_id)
);

    Table "public.detail"
 Column |  Type   | Modifiers
--------+---------+-----------
 con_id | integer |
 ind_id | integer |
Foreign-key constraints:
    "detail_fk1" FOREIGN KEY (con_id) REFERENCES master(con_id)
    "detail_fk2" FOREIGN KEY (ind_id) REFERENCES master(ind_id)

Well, no errors. Let's make sure it works.

test=# insert into detail values (0, 0);
INSERT 0 1
test=# insert into detail values (1, 0);
ERROR:  insert or update on table "detail" violates foreign key constraint "detail_fk1"
DETAIL:  Key (con_id)=(1) is not present in table "master".
test=# insert into detail values (0, 1);
ERROR:  insert or update on table "detail" violates foreign key constraint "detail_fk2"
DETAIL:  Key (ind_id)=(1) is not present in table "master".
test=#

Both columns can be referenced in foreign keys.

Constraint using index

You can add table constraint using existing unique index.

alter table master add constraint master_ind_id_key unique using index master_unique_idx;

    Table "public.master"
 Column |  Type   | Modifiers
--------+---------+-----------
 con_id | integer |
 ind_id | integer |
Indexes:
    "master_con_id_key" UNIQUE CONSTRAINT, btree (con_id)
    "master_ind_id_key" UNIQUE CONSTRAINT, btree (ind_id)
Referenced by:
    TABLE "detail" CONSTRAINT "detail_fk1" FOREIGN KEY (con_id) REFERENCES master(con_id)
    TABLE "detail" CONSTRAINT "detail_fk2" FOREIGN KEY (ind_id) REFERENCES master(ind_id)

Now there is no difference between column constraints description.

Partial indexes

In table constraint declaration you cannot create partial indexes. It comes directly from the definition of create table .... In unique index declaration you can set WHERE clause to create partial index. You can also create index on expression (not only on column) and define some other parameters (collation, sort order, NULLs placement).

You cannot add table constraint using partial index.

alter table master add column part_id integer;
create unique index master_partial_idx on master (part_id) where part_id is not null;

alter table master add constraint master_part_id_key unique using index master_partial_idx;
ERROR:  "master_partial_idx" is a partial index
LINE 1: alter table master add constraint master_part_id_key unique ...
                               ^
DETAIL:  Cannot create a primary key or unique constraint using such an index.
Eugen Konkov
  • 22,193
  • 17
  • 108
  • 158
klin
  • 112,967
  • 15
  • 204
  • 232
47

One more advantage of using UNIQUE INDEX vs. UNIQUE CONSTRAINT is that you can easily DROP/CREATE an index CONCURRENTLY, whereas with a constraint you can't.

Vadim Zingertal
  • 571
  • 4
  • 2
  • 7
    AFAIK it's not possible to drop concurrently a unique index. https://www.postgresql.org/docs/9.3/static/sql-dropindex.html "There are several caveats to be aware of when using this option. Only one index name can be specified, and the CASCADE option is not supported. (Thus, an index that supports a UNIQUE or PRIMARY KEY constraint cannot be dropped this way.)" – Rafał Cieślak Oct 08 '16 at 17:35
  • In Postgres 12.0 I receive no error when attempting to drop a unique index concurrently; the table definition after running the command shows that the index was indeed dropped. `DROP INDEX CONCURRENTLY IF EXISTS idx_name` – Reece Daniels Jul 06 '22 at 09:58
33

Uniqueness is a constraint. It happens to be implemented via the creation of a unique index since an index is quickly able to search all existing values in order to determine if a given value already exists.

Conceptually the index is an implementation detail and uniqueness should be associated only with constraints.

The full text

So speed performance should be same

Eugen Konkov
  • 22,193
  • 17
  • 108
  • 158
  • From that quote I read the speed performance is faster in index and NOT the same. I thought that is the whole reason for index. – Zaffer Mar 14 '22 at 18:33
  • @Zaffer: Probably you confused by `quickly`, it is not equal `quicker`. Quote says that index is used to check that value already exists. And this task is done quickly. Also it says that when you use `unique constraint` under hood it uses `index`. Because of that performance is same. – Eugen Konkov Mar 16 '22 at 08:07
19

Since various people have provided advantages of unique indexes over unique constraints, here's a drawback: a unique constraint can be deferred (only checked at the end of the transaction), a unique index can not be.

Masklinn
  • 34,759
  • 3
  • 38
  • 57
  • How can this be, given that all unique constraints have a unique index? – Chris May 08 '20 at 11:21
  • 2
    Because indexes do not have an API for deferring, only constraints do, so while the deferral machinery exists under the cover to support unique constraints, there's no way to declare an index as deferrable, or to defer it. – Masklinn May 08 '20 at 12:59
  • Interesting observation. So when using constraints (vs indexes) one can have conflicting data during transaction but if it’s fine at the end, then it would succeed? Indexes would fail earlier as I understood. – Tvaroh Mar 24 '21 at 10:15
  • 1
    That is correct, assuming the constraint is deferrable and deferred. Also note that not all constraints are deferrable: `NOT NULL` and `CHECK` constraints are always immediate. – Masklinn Mar 24 '21 at 10:17
  • @Masklinn does user need to do anything to make them deferrable/deferred? Speaking about uniqueness constraints. UPD: found this https://hashrocket.com/blog/posts/deferring-database-constraints – Tvaroh Mar 24 '21 at 10:19
  • You need to create the constraint as `DEFERRABLE` in the first place (the default is `NOT DEFERRABLE`), and either create it as `DEFERRABLE INITIALLY DEFERRED` (in which case it's always deferred by default), or `SET CONSTRAINTS DEFERRED` in the specific transactions where you want to defer the constraint's checking. Which is best depends on your specific use case e.g. whether you always want the constraint to be deferred, or only have a few places where that's a necessity. – Masklinn Mar 24 '21 at 10:27
15

Another thing I've encountered is that you can use sql expressions in unique indexes but not in constraints.

So, this does not work:

CREATE TABLE users (
    name text,
    UNIQUE (lower(name))
);

but following works.

CREATE TABLE users (
    name text
);
CREATE UNIQUE INDEX uq_name on users (lower(name));
김민준
  • 937
  • 11
  • 14
  • I would use the `citext` extension. – ceving Mar 11 '19 at 15:57
  • @ceving it depends on the use case. sometimes you want to preserve casing while ensuring case-insensitive uniqueness – Sampson Crowley Jul 08 '20 at 19:38
  • 1
    I ran into this as well. I was worried that not being able to add the constraint would be a problem but it seems to be working fine. I tried to do: ALTER TABLE films ADD CONSTRAINT unique_file_title UNIQUE USING INDEX lower_title_idx; but got error Cannot create a primary key or unique constraint using such an index. Index contains expressions. I tried inserting case-insensitive data and it seems to work even without the constraint. – RcoderNY Apr 23 '21 at 03:31
  • I needed this specific functionality too, and I could achieve it using function indices as described, while constraints didn't help. – Rafs Feb 28 '23 at 11:17
15

A very minor thing that can be done with constraints only and not with indexes is using the ON CONFLICT ON CONSTRAINT clause (see also this question).

This doesn't work:

CREATE TABLE T (a INT PRIMARY KEY, b INT, c INT);
CREATE UNIQUE INDEX u ON t(b);

INSERT INTO T (a, b, c)
VALUES (1, 2, 3)
ON CONFLICT ON CONSTRAINT u
DO UPDATE SET c = 4
RETURNING *;

It produces:

[42704]: ERROR: constraint "u" for table "t" does not exist

Turn the index into a constraint:

DROP INDEX u;
ALTER TABLE t ADD CONSTRAINT u UNIQUE (b);

And the INSERT statement now works.

Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
5

There is a difference in locking.
Adding an index does not block read access to the table.
Adding a constraint does put a table lock (so all selects are blocked) since it is added via ALTER TABLE.

Bax
  • 4,260
  • 5
  • 43
  • 65
0

I read this in the doc:

ADD table_constraint [ NOT VALID ]

This form adds a new constraint to a table using the same syntax as CREATE TABLE, plus the option NOT VALID, which is currently only allowed for foreign key constraints. If the constraint is marked NOT VALID, the potentially-lengthy initial check to verify that all rows in the table satisfy the constraint is skipped. The constraint will still be enforced against subsequent inserts or updates (that is, they'll fail unless there is a matching row in the referenced table). But the database will not assume that the constraint holds for all rows in the table, until it is validated by using the VALIDATE CONSTRAINT option.

So I think it is what you call "partial uniqueness" by adding a constraint.

And, about how to ensure the uniqueness:

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.

Note: The preferred way to add a unique constraint to a table is ALTER TABLE … ADD CONSTRAINT. The use of indexes to enforce unique constraints could be considered an implementation detail that should not be accessed directly. One should, however, be aware that there’s no need to manually create indexes on unique columns; doing so would just duplicate the automatically-created index.

So we should add constraint, which creates an index, to ensure uniqueness.

How I see this problem?

A "constraint" aims to gramatically ensure that this column should be unique, it establishes a law, a rule; while "index" is semantical, about "how to implement, how to achieve the uniqueness, what does unique means when it comes to implementation". So, the way Postgresql implements it, is very logical: first, you declare that a column should be unique, then, Postgresql adds the implementation of adding an unique index for you.

Community
  • 1
  • 1
WesternGun
  • 11,303
  • 6
  • 88
  • 157
  • 1
    "So I think it is what you call "partial uniqueness" by adding a constraint." indexes can apply to only a well-defined subset of the records through the `where` clause, so you can define that records are unique IFF they satisfy some criteria. This simply disables the constrains for an undefined set of records which predate the constraint being created. It's completely different, and the latter is significantly *less* useful, though it's convenient for progressive migrations I guess. – Masklinn May 09 '20 at 15:53
0

In addition to the other answers, there's a topic of whether unique constraints are also used to speed-up queries as indexes are.

Apparently constraints are actually used for Index Scans as indicated by EXPLAIN:

ALTER TABLE mytable
    ADD CONSTRAINT mytable_uc UNIQUE (other_id, name);

explain select * from mytable
    where name = 'name' and other_id = 154

Result:

Index Scan using mytable_uc on mytable  (cost=0.28..2.29 rows=1 width=101)
  Index Cond: ((other_id = 154) AND ((name)::text = 'name'::text))
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
salmin
  • 457
  • 3
  • 12
-1
SELECT a.phone_number,count(*) FROM public.users a
Group BY phone_number Having count(*)>1;

SELECT a.phone_number,count(*) FROM public.retailers a
Group BY phone_number Having count(*)>1;

select a.phone_number from users a inner join users b
on a.id <> b.id and a.phone_number = b.phone_number order by a.id;


select a.phone_number from retailers a inner join retailers b
on a.id <> b.id and a.phone_number = b.phone_number order by a.id
DELETE FROM
    users a
        USING users b
WHERE
    a.id > b.id
    AND a.phone_number = b.phone_number;
    
DELETE FROM
    retailers a
        USING retailers b
WHERE
    a.id > b.id
    AND a.phone_number = b.phone_number;
    
CREATE UNIQUE INDEX CONCURRENTLY users_phone_number 
ON users (phone_number);

To Verify:

insert into users(name,phone_number,created_at,updated_at) select name,phone_number,created_at,updated_at from users
Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
  • 2
    This question is really old, please pay attention to newer ones. I think you wanted to paste this to other post, because it is OT. – DARK_A Jan 29 '21 at 10:45
  • 1
    If you think that this answer is related to the given question, please add some explanation to it such that others can learn from it – Nico Haase Feb 18 '21 at 12:47