Skip to content

Instantly share code, notes, and snippets.

@sycobuny
Created September 10, 2012 15:59
Show Gist options
  • Select an option

  • Save sycobuny/3691735 to your computer and use it in GitHub Desktop.

Select an option

Save sycobuny/3691735 to your computer and use it in GitHub Desktop.
Possible Solution to Unique-With-NULL Problem
-- you may have to declare the function after the table exists.
CREATE FUNCTION check_unique_ex(TEXT, TEXT, TEXT)
RETURNS BOOLEAN
LANGUAGE SQL
AS $BODY$
SELECT EXISTS (
SELECT 1
FROM ex
WHERE a IS NOT DISTINCT FROM $1 AND
b IS NOT DISTINCT FROM $2 AND
C IS NOT DISTINCT FROM $3
);
$BODY$;
CREATE TABLE ex (
a TEXT,
b TEXT,
c TEXT,
-- if you have to move the function declaration later,
-- this will have to be moved to an ALTER TABLE
CONSTRAINT unique_with_nulls CHECK (check_unique_ex(a, b, c))
);
-- these may or may not improve your performance.
-- not sure if a multi-column index would do better/worse
CREATE INDEX idx_a ON ex (a);
CREATE INDEX idx_b ON ex (b);
CREATE INDEX idx_c ON ex (c);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment