304

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.

1
  • 3
    create unique index on foo_table (permalink)
    – user330315
    Commented Oct 20, 2014 at 17:48

5 Answers 5

442

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

ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);

Thanks Fred.

1
  • 12
    In case you need to reverse this. ALTER TABLE the_table DROP CONSTRAINT IF EXISTS constraint_name;
    – vkozyrev
    Commented Nov 5, 2022 at 6:20
381

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

ALTER TABLE foo ADD UNIQUE (thecolumn);
2
  • 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
    Commented Jan 16, 2020 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
    Commented Jul 6, 2020 at 11:11
65

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);
1
  • 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); Commented Oct 6, 2017 at 22:22
8

Try the following

ALTER TABLE table_name ADD UNIQUE (column_name);
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.