Skip to content

Instantly share code, notes, and snippets.

@cecilemuller
Created July 10, 2012 05:44
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cecilemuller/3081392 to your computer and use it in GitHub Desktop.
Save cecilemuller/3081392 to your computer and use it in GitHub Desktop.
PostgreSQL: UPDATE if the row exists, INSERT if it doesn't exists (UPSERT)
CREATE OR REPLACE FUNCTION upsert_tableName(arg1 type, arg2 type) RETURNS VOID AS $$
DECLARE
BEGIN
UPDATE tableName SET col1 = value WHERE colX = arg1 and colY = arg2;
IF NOT FOUND THEN
INSERT INTO tableName values (value, arg1, arg2);
END IF;
END;
$$ LANGUAGE 'plpgsql';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment