Skip to content

Instantly share code, notes, and snippets.

@petetronic
Last active December 8, 2015 20:16
Show Gist options
  • Save petetronic/c6274f33ffea1c7d1956 to your computer and use it in GitHub Desktop.
Save petetronic/c6274f33ffea1c7d1956 to your computer and use it in GitHub Desktop.
PostgreSQL conditional anonymous code block
DO $$
DECLARE updated_rows INT;
BEGIN
UPDATE some_table
SET some_column = 'new'
WHERE some_column = 'old';
GET DIAGNOSTICS updated_rows = ROW_COUNT;
-- Replace 1 with expected row count
IF updated_rows <> 1 THEN
RAISE EXCEPTION 'Unexpected number of rows would be modified = %', updated_rows;
ELSE
RAISE NOTICE 'Success. Updated % row(s)', updated_rows;
END IF;
END;
$$;
@huaweigu
Copy link

huaweigu commented Dec 8, 2015

👍

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