Question

I have these entries in a field in one table under a DB running Postgres 9.4:

copy schema_name.table_name to '/path/path2/path3/path4/reports/export" 

and would like to replace ONLY the word "reports" by "reports_test"

What would be the proper way to do this?

I understand is a regular expression in an SQL update query but not exactly sure.

Was it helpful?

Solution

This replacement can be done with:

UPDATE tableName SET fieldName =
     regexp_replace(fieldName, '\yreports\y', 'reports_test', 'g');

From the documentation:

\y matches only at the beginning or end of a word

The last argument 'g' is meant to replace all occurrences, otherwise it would replace only the first found.

You may also add a WHERE clause to limit the rows updated to those that match:

UPDATE tableName SET fieldName =
     regexp_replace(fieldName, '\yreports\y', 'reports_test', 'g')
WHERE fieldName ~ '\yreports\y';
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top