Sobes.tech
Senior

How to add a uniqueness constraint on a combination of two columns in PostgreSQL, where individual values can repeat, but pairs cannot?

sobes.tech AI

Answer from AI

In PostgreSQL, to ensure the uniqueness of a combination of values from two columns, a UNIQUE constraint is used on the pair of these columns. This guarantees that each pair of values will be unique, even if individual values in the columns can repeat.

Example SQL query:

ALTER TABLE your_table_name
ADD CONSTRAINT unique_col1_col2 UNIQUE (column1, column2);

If the table is created from scratch, you can specify the constraint immediately:

CREATE TABLE your_table_name (
    id SERIAL PRIMARY KEY,
    column1 TYPE,
    column2 TYPE,
    -- other columns
    CONSTRAINT unique_col1_col2 UNIQUE (column1, column2)
);

Thus, the database will not allow inserting rows with a repeating combination of values in these two columns.

How to add a uniqueness constraint on a combination… - sobes.tech