I have two tables named playersand matchesin Postgres DB as follows:
CREATE TABLE players (
name text NOT NULL,
id serial PRIMARY KEY
);
CREATE TABLE matches (
winner int REFERENCES players (id),
loser int REFERENCES players (id),
CONSTRAINT unique_matches
PRIMARY KEY (winner, loser)
);
How can I guarantee that matchesonly a unique combination is used for the primary key (winner, loser)or (loser, winner), so that the table matcheswill not allow insertion:
INSERT INTO matches VALUES (2, 1);
If it already has a string containing VALUES (1, 2), for example:
winner | loser
--------+-------
1 | 2
The goal is to avoid entering matches between the same players.
source
share