How to implement ternary conditional operator in MySQL

MysqlConditional Operator

Mysql Problem Overview


I want to implement ternary conditional operator in MySQL. I have a table in which one field id exist. Its value may be null. I want to display id in ternary conditional format like this:

select id = id == null ? 0 : id;

Is it possible in MySQL?

Mysql Solutions


Solution 1 - Mysql

Try this :

select if(Id is null, 0, id) as Id;

Solution 2 - Mysql

The documentation is your friend; you should read it!

It says:

> IFNULL(expr1,expr2) > > If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns > expr2.

And then lots of examples. This is equivalent to using a ternary conditional with a comparison to NULL and the comparison subject as the second operand; that it doesn't happen to use the symbols ? and : to get you there is not really relevant to anything.

So, in your case:

SELECT IFNULL(`id`, 0) FROM `table`

If you're desperate to provide three operands explicitly (why?!), then switch to IF:

SELECT IF(`id` IS NULL, 0, `id`) FROM `table`

Solution 3 - Mysql

There are two ways that you can implement the same logic as a ternary operator:

  1. Use the IF function, eg. IF(expression, true result, false result)

  2. Use the CASE expression, eg.

    CASE WHEN expression THEN <true result> ELSE <false_result> END
    

When you are checking for NULL then you can use the IFNULL or COALESCE functions, eg.

IFNULL(ID, 0)
COALESCE(ID, 0)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1086355View Question on Stackoverflow
Solution 1 - MysqlDewasish MitrukaView Answer on Stackoverflow
Solution 2 - MysqlLightness Races in OrbitView Answer on Stackoverflow
Solution 3 - Mysqla'rView Answer on Stackoverflow