Skip to content

Instantly share code, notes, and snippets.

@jdforsythe
Created November 16, 2016 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdforsythe/7b4f91353ac45950a0a546df1e043aef to your computer and use it in GitHub Desktop.
Save jdforsythe/7b4f91353ac45950a0a546df1e043aef to your computer and use it in GitHub Desktop.
PostgreSQL constraint - column A unique for rows where column B is true
-- 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