In postgresql, how do I replace all instances of a string within a database column?
Say I want to replace all instances of cat
with dog
, for example.
What's the best way to do this?
In postgresql, how do I replace all instances of a string within a database column?
Say I want to replace all instances of cat
with dog
, for example.
What's the best way to do this?
Here is an example that replaces all instances of 1 or more white space characters in a column with an underscore using regular expression -
The Regular Expression Way
If you need stricter replacement matching, PostgreSQL's
regexp_replace
function can match using POSIX regular expression patterns. It has the syntax regexp_replace(source, pattern, replacement [, flags ]).I will use flags
i
andg
for case-insensitive and global matching, respectively. I will also use\m
and\M
to match the beginning and the end of a word, respectively.There are usually quite a few gotchas when performing regex replacment. Let's see how easy it is to replace a cat with a dog.
Even after all of that, there is at least one unresolved condition. For example, sentences that begin with "Cat" will be replaced with lower-case "dog" which break sentence capitalization.
Check out the current PostgreSQL pattern matching docs for all the details.
Update entire column with replacement text
Given my examples, maybe the safest option would be:
You can use the
replace
functionThe function definition is as follows (got from here):
and returns the modified text. You can also check out this sql fiddle.
You want to use postgresql's replace function:
for instance :
Be aware, though, that this will be a string-to-string replacement, so 'category' will become 'dogegory'. the regexp_replace function may help you define a stricter match pattern for what you want to replace.