0

I try to replace null value with string 0000

SELECT customer_id
FROM customer c 
LEFT JOIN user u ON u.idc = c.id
WHERE deleted = 0

I try with

IFNULL(c.customer_id,'0000')

COALESCE(c.customer_id,'0000')

REPLACE(c.customer_id,'','0000')

but don't work.

Result should be:

(Before)    (After)
null        0000
1234        1234
            0000

What should I do ?

10
  • COALESECE() should be getting the job done. Can you post some sample data? Commented Feb 22, 2016 at 9:31
  • 1
    Possible duplicate of MYSQL: replace null with 0? Commented Feb 22, 2016 at 9:32
  • 1
    What the data in the tables? the query looks fine Commented Feb 22, 2016 at 9:33
  • @TimBiegeleisen I update sample data. Commented Feb 22, 2016 at 9:34
  • @PathikVejani Should be same but in my case not return 0000 it return empty field Commented Feb 22, 2016 at 9:35

4 Answers 4

1

Use inline IF to check for null and empty strings and if exists then return '0000'.

SELECT IF(customer_id='' OR customer_id IS NULL,'0000',customer_id)
FROM customer c 
LEFT JOIN user u ON u.idc = c.id
WHERE deleted = 0
Sign up to request clarification or add additional context in comments.

1 Comment

It's work and easy for me same as @h2ooooooo 's answer :)
1
SELECT CASE 
WHEN customer_id ='' THEN replace(customer_id,' ','0000')
WHEN customer_id is null THEN replace (customer_id,null,'0000')
end AS customer_id
FROM customer c 
LEFT JOIN user u ON u.idc = c.id
WHERE deleted = 0

Comments

0

you can check for empty first like this:

SELECT case when customer_id='' then '0000' else COALESCE(c.customer_id,'0000') end 
FROM customer c 
LEFT JOIN user u ON u.idc = c.id
WHERE deleted = 0

1 Comment

I didn't downvote you, but I suspect the reason is that the OP is already essentially using your query and still did not get the desired result.
0

If you have both null values and empty strings, then you need to combine coalesce() with string replacement:

SELECT if(coalesce(customer_id,'0000')='','0000',coalesce(customer_id,'0000')) as customer_id
FROM customer c 
LEFT JOIN user u ON u.idc = c.id
WHERE deleted = 0

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.