Created
November 16, 2016 21:35
-
-
Save jdforsythe/7b4f91353ac45950a0a546df1e043aef to your computer and use it in GitHub Desktop.
PostgreSQL constraint - column A unique for rows where column B is true
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Scenario: There should only exist one record for each distinct value for column A that has column B set to true. There can be any number of records for each distinct value for column A where column B is false. | |
-- i.e. there can be only one active record (column B true) for each distinct value of column A | |
DROP TABLE IF EXISTS test; | |
CREATE TABLE test ( | |
"a" CHARACTER VARYING(3) NOT NULL, | |
"b" BOOLEAN NOT NULL DEFAULT TRUE | |
); | |
INSERT INTO test (a,b) VALUES ('1', true); | |
INSERT INTO test (a,b) VALUES ('1', false); | |
INSERT INTO test (a,b) VALUES ('1', false); | |
INSERT INTO test (a,b) VALUES ('1', true); | |
SELECT ( | |
CASE WHEN COUNT(*) = 4 THEN 'PASS - Inserted without error without constraint' ELSE 'FAIL - Did not insert' END | |
) AS "result" FROM test; | |
TRUNCATE TABLE test; | |
CREATE UNIQUE INDEX ON test (a,b) WHERE b = true; | |
INSERT INTO test (a,b) VALUES ('1', true); | |
INSERT INTO test (a,b) VALUES ('1', false); | |
INSERT INTO test (a,b) VALUES ('1', false); | |
INSERT INTO test (a,b) VALUES ('1', true); | |
SELECT ( | |
CASE WHEN COUNT(*) = 4 THEN 'FAIL - Inserted without error with constraint' ELSE 'PASS - Did not insert with constraint' END | |
) AS "result" FROM test; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment