Doadc Doadc - 9 months ago 39
SQL Question

Replace unknown value in SQL query with PostgreSQL

How can I use SQL/PostgreSQL to do something like this (psuedo code):

UPDATE table
SET content = replace(content, 'padding-top: $VAR', 'padding-top: 30px')
WHERE user = 1;

The $VAR is an unknown value, like 80%, 50% or 80px. How could I do this?


You could use regexp_replace:

UPDATE table
SET content = regexp_replace(content, '^padding-top: .*$', 'padding-top: 30px')
WHERE user = 1;

Note that as its name suggests, regexp_replace takes a regular expression. So I am using ^, $ for the beginning and the end, and .* which means "match with any sequence of characters" (. means "match with any character" and * means "match the previous symbol as many times as possible").