Search code examples
mysqlsqlselectif-statementcase

SQL statement equivalent to ternary operator


I would like to create a statement that is equivalent to (x - y == 0) ? return 0 : return 100 in MySQL. Something that might look like this:

SELECT id, [(integer_val - 10 == 0) ? 0 : 100] AS new_val FROM my_table

I want to compare an attribute in each row to a certain number, and if the difference between that number and the number in the row is 0, I want it to give me 0, otherwise, I want it to give me 100.

Example:

Applying this query on my_table (with 10 being the 'compared to' number):

id  |   integer_val
===================
1   10
2   10
3   3
4   9

Would return this:

id  |   new_val
===================
1   100
2   100
3   0
4   0

How can I do this?


Solution

  • Try this:

    SELECT id, IF(integer_val = 10, 100, 0) AS new_val 
    FROM my_table;
    

    OR

    SELECT id, (CASE WHEN integer_val = 10 THEN 100 ELSE 0 END) AS new_val 
    FROM my_table;