Skip to content

Instantly share code, notes, and snippets.

@huaweigu
Forked from petetronic/gist:c6274f33ffea1c7d1956
Created December 8, 2015 20:15
Show Gist options
  • Save huaweigu/8298b3df1d80b4e6c2b1 to your computer and use it in GitHub Desktop.
Save huaweigu/8298b3df1d80b4e6c2b1 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;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment