13

I have two SQL statements:

CREATE TABLE legs(legid INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
                  playerid1 INT NOT NULL REFERENCES players(playerid),
                  playerid2 INT NOT NULL REFERENCES players(playerid),
                  added TIMESTAMP AS CURRENT_TIMESTAMP NOT NULL);

ALTER TABLE legs ADD CONSTRAINT distinct_players CHECK(playerid1 <> playerid2);

I am 99% sure I should be able to condense them into one, i.e:

CREATE TABLE table(...
                   playerid2 INT NOT NULL REFERENCES players(playerid) CHECK(playerid1 <> playerid2),
                   ...);

However, I am consistently getting a syntax error. AFAIK, this is where the constraint should be.

c24w
  • 7,421
  • 7
  • 39
  • 47

1 Answers1

22
CREATE TABLE legs(legid INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
                  playerid1 INT NOT NULL REFERENCES players(playerid),
                  playerid2 INT NOT NULL REFERENCES players(playerid),
                  added TIMESTAMP AS CURRENT_TIMESTAMP NOT NULL,
                  CHECK (playerid1 <> playerid2));
  • The check constraints have to all be at the bottom of the table and cannot be intermixed with the columns, as CHECK constraints can be intermixed in PostgreSQL. – Kent Bull Apr 11 '17 at 19:20