316

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) Commented Oct 20, 2014 at 17:48

5 Answers 5

457

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

ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn); 

Thanks Fred.

Sign up to request clarification or add additional context in comments.

1 Comment

In case you need to reverse this. ALTER TABLE the_table DROP CONSTRAINT IF EXISTS constraint_name;
392

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

ALTER TABLE foo ADD UNIQUE (thecolumn); 

2 Comments

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
When I use the syntax above, Postgress creates the new contraint with the name mytable_mycolumn_key I'm quite happy with that :-)
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 Comment

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);
9

Try the following

ALTER TABLE table_name ADD UNIQUE (column_name); 

Comments

5

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.