Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[PostgreSQL: create constraint if not exists] not sure of sql compatibility with other engines #postgres #constraint #sql
// vim: syntax=sql
CREATE OR REPLACE FUNCTION create_constraint_if_not_exists (t_name text, c_name text, constraint_sql text)
RETURNS void
AS
$BODY$
BEGIN
-- Look for our constraint
IF NOT EXISTS (SELECT constraint_name
FROM information_schema.constraint_column_usage
WHERE constraint_name = c_name) THEN
EXECUTE 'ALTER TABLE ' || t_name || ' ADD CONSTRAINT ' || c_name || ' ' || constraint_sql;
END IF;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;
SELECT create_constraint_if_not_exists('foo', 'bar', 'CHECK (foobies < 100);');
@nsw-axelor

This comment has been minimized.

Copy link

@nsw-axelor nsw-axelor commented Feb 12, 2021

Yes, It works in PostgreSQL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment