2

I have a post table which has a title and a description.

My goal is to clean the description by applying a set of rules. For simplicity let's say that I'd like to apply following rules:

REPLACE "H" with "Z"
REPLACE "Z" with "C"
REPLACE "C" with "X"

So if I have the string "Hello world", the output would be "Xello world" after applying the three rules.

Hello world -> Zello world -> Cello world -> Xello world

I know I can achieve this using 3 independent update queries

UPDATE post
SET description = REPLACE(description, 'H', 'Z');

UPDATE post
SET description = REPLACE(description, 'Z', 'C');

UPDATE post
SET description = REPLACE(description, 'C', 'X');

But I am wondering if there is a better way to achieve what I want. Maybe I need a procedure? a function? store the middle result in a variable?

I am using Postgres 12.

3 Answers 3

4

As I understand your requirement, what you want is all the characters 'H', 'Z' and 'C' to be finally replaced by X.
You can do it with the function TRANSLATE():

UPDATE post
SET description = translate(description, 'HZC', 'XXX');
Sign up to request clarification or add additional context in comments.

Comments

3

You can nest the replace calls:

UPDATE post
  SET description = replace(replace(replace(description, 'H', 'Z'), 'Z', 'C'), 'C', 'X')

Comments

1

How about

UPDATE post
SET description = REPLACE(REPLACE(REPLACE(description, 'H', 'Z'), 'Z', 'C'), 'C', 'X');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.