Sobes.tech
Senior

Kuidas lisada PostgreSQL-i unamatuse piirang kahe veeru kombinatsioonile, kus üksikud väärtused võivad korduda, kuid paarid — mitte?

sobes.tech AI

Vastus AI-lt

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

Example SQL query:

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

If the table is created from scratch, the constraint can be specified immediately:

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

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