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 ?

May
  • 5
  • 1
  • 5

4 Answers4

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
Abhishek Ginani
  • 4,511
  • 4
  • 23
  • 35
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
Ankit Agrawal
  • 2,426
  • 1
  • 13
  • 27
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
Gouda Elalfy
  • 6,888
  • 1
  • 26
  • 38
  • 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. – Tim Biegeleisen Feb 22 '16 at 09:39
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
Shadow
  • 33,525
  • 10
  • 51
  • 64