282

I have a table in PostgreSQL where the schema looks like this:

CREATE TABLE "foo_table" (
    "id" serial NOT NULL PRIMARY KEY,
    "permalink" varchar(200) NOT NULL,
    "text" varchar(512) NOT NULL,
    "timestamp" timestamp with time zone NOT NULL
)

Now I want to make the permalink unique across the table by ALTER-ing the table.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Baishampayan Ghose
  • 19,928
  • 10
  • 56
  • 60

5 Answers5

413

I figured it out from the PostgreSQL docs, the exact syntax is:

ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);

Thanks Fred.

Community
  • 1
  • 1
Baishampayan Ghose
  • 19,928
  • 10
  • 56
  • 60
  • 7
    In case you need to reverse this. `ALTER TABLE the_table DROP CONSTRAINT IF EXISTS constraint_name;` – vkozyrev Nov 05 '22 at 06:20
352

Or, have the DB automatically assign a constraint name using:

ALTER TABLE foo ADD UNIQUE (thecolumn);
rdrey
  • 9,379
  • 4
  • 40
  • 52
Clint Pachl
  • 10,848
  • 6
  • 41
  • 42
  • 2
    If you do this, postgres is going to create the constraint but is the name is going to "automatically" assign is the word "add". I have just tried it – Santi Jan 16 '20 at 23:44
  • 7
    When I use the syntax above, Postgress creates the new contraint with the name `mytable_mycolumn_key` I'm quite happy with that :-) – Adam Jul 06 '20 at 11:11
63

it's also possible to create a unique constraint of more than 1 column:

ALTER TABLE the_table 
    ADD CONSTRAINT constraint_name UNIQUE (column1, column2);
isapir
  • 21,295
  • 13
  • 115
  • 116
Stefan
  • 631
  • 5
  • 2
  • This doesn't seem to work for something like: `ALTER TABLE actions ADD CONSTRAINT actions_unique_constraint UNIQUE (payload::text, name);` or `ALTER TABLE actions ADD CONSTRAINT actions_unique_constraint UNIQUE ((payload::text), name);` – writofmandamus Oct 06 '17 at 22:22
5

Try the following

ALTER TABLE table_name ADD UNIQUE (column_name);
1

To make a column unique in a PostgreSQL table, you can use the ALTER TABLE statement with the ADD CONSTRAINT clause.

Here's an example SQL statement

ALTER TABLE mytable
ADD CONSTRAINT unique_column_name UNIQUE (column_name);

In above statement, mytable is the name of the table you want to modify, column_name is the name of the column you want to make unique, and unique_column_name is a name you choose for the unique constraint.

If there are already duplicate values in the column you want to make unique, the ALTER TABLE statement will fail. You will need to remove or modify the duplicates before you can add the unique constraint.

Also, keep in mind that making a column unique will create an index on that column, which can impact performance if the table is very large or the column is frequently updated.

helvete
  • 2,455
  • 13
  • 33
  • 37
Juyel
  • 31
  • 3