How do I ALTER a PostgreSQL table and make a column unique?

SqlPostgresqlUnique Constraint

Sql Problem Overview


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.

Sql Solutions


Solution 1 - Sql

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

ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);

Thanks Fred.

Solution 2 - Sql

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

ALTER TABLE foo ADD UNIQUE (thecolumn);

Solution 3 - Sql

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBaishampayan GhoseView Question on Stackoverflow
Solution 1 - SqlBaishampayan GhoseView Answer on Stackoverflow
Solution 2 - SqlClint PachlView Answer on Stackoverflow
Solution 3 - SqlStefanView Answer on Stackoverflow