John Magnolia
John Magnolia

Reputation: 16793

mysql if not null, 0 or ""

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.

Upvotes: 9

Views: 10502

Answers (4)

tim
tim

Reputation: 2724

Could this work for you?

SELECT *
FROM table
WHERE id IN ('21')
AND content_id IN (NULL, 0, '');

Upvotes: 0

fthiella
fthiella

Reputation: 49049

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 content_id is either '0' or ''
  • Null if content_id IS Null
  • False otherwise.

If it's Null, COALESCE will return 1 here, which is equivalent to True.

Upvotes: 4

bonCodigo
bonCodigo

Reputation: 14361

You can try COALESCE:

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

Upvotes: 2

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181280

You can use IFNULL function in MySQL.

select ____
  from tbl
 where IFNULL(content_id, 0) = 0

Upvotes: 9

Related Questions