Use variable set by psql meta-command inside of DO block

Answer DO expects a string literal with plpgsql code. Symbols are not substituted inside strings in psql. You could concatenate the whole string into a psql variable and then execute it. How to concatenate psql variables? Pretty multi-line format is not possible, because (per documentation): But in any case, the arguments of a meta-command cannot … Read more

Flatten aggregated key/value pairs from a JSONB field?

This particular case The function below dynamically creates a view based on a table: create or replace function create_totals_view(table_name text) returns void language plpgsql as $$ declare s text; begin execute format ($fmt$ select string_agg(format(‘star_pu->>”%s” “%s”‘, key, key), ‘,’) from ( select distinct key from %s, json_each(star_pu) order by 1 ) s; $fmt$, ‘%s’, ‘%s’, … Read more

How to perform update operations on columns of type JSONB in Postgres 9.4

If you’re able to upgrade to Postgresql 9.5, the jsonb_set command is available, as others have mentioned. In each of the following SQL statements, I’ve omitted the where clause for brevity; obviously, you’d want to add that back. Update name: UPDATE test SET data = jsonb_set(data, ‘{name}’, ‘”my-other-name”‘); Replace the tags (as oppose to adding … Read more