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.
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().
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With