Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Ternary operations

Tags:

sql

mysql

In C++, you can do this:

T.x = (T.y > 1 && (T.x - T.y < 0)) ? 0 : (T.x - T.y)

which in [almost] plain english, is

if T.y > 1 and T.x-T.y < 0 then
    set T.x to 0
else 
    set T.x to T.x-T.y 

Is it possible to do the same thing using just SQL, without using stored procs or triggers?

like image 824
John Avatar asked Jan 27 '12 06:01

John


2 Answers

Use the CASE statement:

CASE WHEN T.y > 1 AND (T.x - T.y) < 0 THEN 0 ELSE (T.x - T.y) END
like image 88
ta.speot.is Avatar answered Nov 15 '22 19:11

ta.speot.is


Yes its possible, take a look at the documentation, it says:

IF(expr1,expr2,expr3)

If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2; otherwise it returns expr3.

This untested code should be your case:

SELECT IF(((T.y > 1) and (T.x-T.y < 0)), 0, (T.x-T.y))
like image 42
CloudyMarble Avatar answered Nov 15 '22 20:11

CloudyMarble