Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I make a column unique in an existing table?

First we write ALTER TABLE, then we list the name of the table (in our example: product ), and next we add the clause ADD CONSTRAINT with the name of the unique constraint (in our example: UQ_product_name ). This is followed by the UNIQUE keyword with column/columns (in our example it is column: name ) in parentheses.

How do I make two columns unique in PostgreSQL?

In Postgresql, we can make two-column as unique using the UNIQUE keyword or function. Let's create a table named two_unq. CREATE TABLE emp_data ( id SERIAL, emp_name VARCHAR , email VARCHAR (50), UNIQUE(emp_name,email )); In the above code, we are creating emp_name, email as the unique column using the UNIQUE().

How do I change a table column in PostgreSQL?

First, specify the name of the table to which the column you want to change belongs in the ALTER TABLE clause. Second, give the name of column whose data type will be changed in the ALTER COLUMN clause. Third, provide the new data type for the column after the TYPE keyword.


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

ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);

Thanks Fred.


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

ALTER TABLE foo ADD UNIQUE (thecolumn);

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