Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql if not null, 0 or ""

Tags:

mysql

isnull

SELECT * 
  FROM table WHERE id IN ('21') 
   AND (content_id IS NULL OR content_id = 0 OR content_id = '')

Is there a shorter way of writing this condition.

I have a int() column that could be either: NULL, 0 or EMPTY.

like image 569
John Magnolia Avatar asked Feb 05 '13 17:02

John Magnolia


3 Answers

You can use IFNULL function in MySQL.

select ____
  from tbl
 where IFNULL(content_id, 0) = 0
like image 58
Pablo Santa Cruz Avatar answered Sep 23 '22 17:09

Pablo Santa Cruz


I think the shorter way is this:

SELECT * 
FROM table
WHERE id IN ('21')
      AND COALESCE(content_id IN ('0', ''), 1)

content_id IN ('0', '') may assume these values:

  • True if conent_id is either '0' or ''
  • Null if conent_id IS Null
  • False otherwise.

If it's Null, with COALESCE I'm returning 1, which is equivalent to True.

like image 29
fthiella Avatar answered Sep 23 '22 17:09

fthiella


You can try COALESCE:

SELECT * FROM table WHERE id IN ('21') 
AND COALESCE(content_id,0) =0;
like image 20
bonCodigo Avatar answered Sep 20 '22 17:09

bonCodigo