2

How do I substitute multiple values in Postgres? I need to do something like the following:

In column C
Case current value = x then replace by a
else if current value is y then replace by b
else if current value is z then replace by c...

2 Answers 2

2

Use CASE WHEN:

UPDATE table_name
SET column_name =
      CASE WHEN column_name = 'x' THEN 'a'
           WHEN column_name = 'y' THEN 'b'
           WHEN column_name = 'z' THEN 'c'
           ...
           ELSE column_name                 -- default
     END
-- WHERE id = ?

LiveDemo

Sign up to request clarification or add additional context in comments.

1 Comment

This is a perfect solution with excellent performance. Thanks lad2025.
1

If you happen to be working with text (or something that can be cast to text) you can try the translate function.

translate(string text, from text, to text) text:

Any character in string that matches a character in the from set is replaced by the corresponding character in the to set. If from is longer than to, occurrences of the extra characters in from are removed. translate('12345', '143', 'ax') a2x5`

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.