Skip to content

Instantly share code, notes, and snippets.

@estysdesu
Last active September 13, 2023 00:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save estysdesu/e64cd53a174ae1864eef099510f5dfc2 to your computer and use it in GitHub Desktop.
Save estysdesu/e64cd53a174ae1864eef099510f5dfc2 to your computer and use it in GitHub Desktop.
[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
Copy link

Yes, It works in PostgreSQL

@junghyun12
Copy link

👍 nice!

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