Skip to content

Instantly share code, notes, and snippets.

@victorcrbt
Last active May 1, 2020 17:17
Show Gist options
  • Save victorcrbt/8c3a0ed2d6167d82c21d8717b047f1da to your computer and use it in GitHub Desktop.
Save victorcrbt/8c3a0ed2d6167d82c21d8717b047f1da to your computer and use it in GitHub Desktop.
Conditional PosgreSQL not null column based on value of another table.
CREATE OR REPLACE FUNCTION checkClientType(int) RETURNS varchar as $$
DECLARE
type varchar;
BEGIN
SELECT client_type INTO type FROM clients WHERE id = $1;
RETURN type;
END;
$$ LANGUAGE plpgsql;
CREATE TABLE aditional_info (
id SERIAL NOT NULL UNIQUE,
client_id int REFERENCES clients(id) ON DELETE SET NULL ON UPDATE CASCADE,
rg varchar(10) NOT NULL,
issuing_body varchar NOT NULL,
birth_date timestamp NOT NULL,
municipal_registration varchar,
CONSTRAINT not_null_municipal_registration CHECK(CASE WHEN checkClientType(client_id) = 'J' THEN municipal_registration IS NOT NULL END)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment