Skip to content

Instantly share code, notes, and snippets.

@jimytc
Created March 24, 2016 16:33
Show Gist options
  • Save jimytc/e4742bf95e7e25bf10a0 to your computer and use it in GitHub Desktop.
Save jimytc/e4742bf95e7e25bf10a0 to your computer and use it in GitHub Desktop.
Use PL/PGSQL to do UPSERT
CREATE OR REPLACE FUNCTION upsert(target_id INT, type_value TEXT) RETURNS VOID AS $$
BEGIN
-- Try update first
UPDATE creation_metadata SET category = type_value
WHERE creation_id = target_id;
-- Return if UPDATE command runs successfully
IF FOUND THEN
RETURN;
END IF;
-- Since there's no record in creation_metada
-- We then add new row with INSERT command
INSERT INTO creation_metadata (creation_id, category)
VALUES (target_id, type_value);
END;co
$$ LANGUAGE 'plpgsql';
SELECT upsert(id, type) FROM creations
WHERE type IS NOT NULL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment