Search code examples
mysqlsqlmysql-error-1064

Replace count 0 with 'N/A' in mysql?


I my following query, the last column returns the count of the instances, for this instances with 0 count I would like to replace them with 'N/A'?

This query does not seems to work

select m.id, m.desc, count(IF(i.id is NULL,'N/A',i.id)) as quant
from menu m left join items i
on m.id = i.id
group by m.id
order by m.id;

The above query outputs as

============================
m.id     |c.desc     | qaunt
============================
1234     | Shoes     | 1
1235     | Socks     | 2
1236     | Clothes   | 0
===========================

Expected result:

============================
m.id     |m.desc     | qaunt
============================
1234     | Shoes     | 1
1235     | Socks     | 2
1236     | Clothes   | N/A
===========================

Could you please suggest me the changes in the above query


Solution

  • (This is tested) Your query is counting the results of the if, and I think you want the inverse. I am using a pairing of IFNULL and NULLIF, which together say "if the count is zero, translate that to NULL. Then if it's NULL, use "N/A" for this column.

    select m.id, m.desc, 
    IFNULL(NULLIF(count(i.id), 0), "N/A") as quant
    from menu m left join items i
    on m.id = i.id
    group by m.id
    order by m.id;
    

    To be pedantic for mysql, you can ensure that the column is always a string via cast():

    IFNULL(NULLIF(CAST(count(i.id) AS char), "0"), "N/A") as quant
    

    This has the benefit of only counting once and no subquery.