0

I'm trying to replace all values in a column where the value is 0 with NULL

SELECT score
REPLACE(score, 0, ISNULL)
FROM kpis
WHERE score=0

or

SELECT score
REPLACE(score, 0, ISNULL)
FROM kpis

But I get a syntax error:

ERROR:  syntax error at or near "REPLACE"
LINE 2: REPLACE(score, 0, ISNULL)
2
  • Use a case expression instead. (Also, REPLACE is for strings, not integers.) Commented Mar 24, 2021 at 9:11
  • 1
    It's unclear to me if you want to just return NULL in the SELECT, or permanently change the values in the table (i.e. run an UPDATE) Commented Mar 24, 2021 at 9:47

4 Answers 4

2

You can use nullif() which is functionally equivalent to a CASE expression, but a bit shorter to write.

SELECT nullif(score, 0) as score
FROM kpis
Sign up to request clarification or add additional context in comments.

Comments

2

Replace all values in a column where the value is 0 with NULL

update kpis set score = NULL where score = 0;

Replace all integer values in a column with NULL

update kpis set score = NULL where score ~ '^[0-9]*$'

Comments

1

use case when

SELECT 
case when score = 0 then null else score end as score
from kpis 

Comments

1

Instead of replace you can use NULLIF(). Below query will set score=null when score is 0.

update kpis set score=NULLIF(score, 0)

Or you can simple use below query as suggested by @Sas.

update kpis set score = NULL where score = 0;

3 Comments

This is wrong. coalesce() returns the first non-null value, so your expression will always return the score or 0 - but never NULL
You are absolutely right. I have changed my answer. Thanks a ton.
Note that this will update the whole table, even if you aren't changing the score. Better is to apply a WHERE clause as in one of the other answers, at which point you don't need the NULLIF.

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.