Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 790
chipit24 Avatar asked Dec 05 '14 04:12

chipit24


People also ask

Is there a ternary operator in SQL?

There's no ternary operator in T-SQL.

What can I use instead of a ternary operator?

The alternative to the ternary operation is to use the && (AND) operation. Because the AND operator will short-circuit if the left-operand is falsey, it acts identically to the first part of the ternary operator.

Which conditional statement is similar with ternary operator?

Conditional or Ternary Operator (?:) in C/C++ The conditional operator is kind of similar to the if-else statement as it does follow the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.

Is the IF statement the same as the ternary operator?

The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way. First, you need to write a conditional expression that evaluates into either true or false .


3 Answers

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;
like image 107
Saharsh Shah Avatar answered Oct 13 '22 15:10

Saharsh Shah


Use case when statement:

select *, (case when integer_val = 10 then 100 else 0 end) as New_Val 
from yourtable
like image 4
Deep Avatar answered Oct 13 '22 15:10

Deep


Try using the IF function:

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

(I stuck with your condition expression, but it can be simplified a bit since integer_value - 10 = 0 has exactly the same truth value as integer_value = 10.)

Note that the IF function is different from MySQL's IF statement used for stored programs.

like image 2
Ted Hopp Avatar answered Oct 13 '22 15:10

Ted Hopp