Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite if statement in WHERE clause

I know I can use CASE statement in an SQLite query but I don't know how to built it in a WHERE clause.

Actually I have this in a long WHERE clause (this is just the part concerned by the question):

AND (%d >= (wines.year + wines.maturity)) AND (%d < (wines.year + wines.apogee))

In fact I want just that :

AND (%d >= (wines.year + wines.maturity))

=> if wines.apogee IS NULL

or also:

AND (%d >= (wines.year + wines.maturity)) AND (%d < (wines.year + wines.apogee))

=> if wines.apogee IS NOT NULL

How to use the CASE statement in this case to test if wines.apogee IS NOT NULL and add the second part of the request in this case ?

Thanks !

like image 846
alex.bour Avatar asked Oct 27 '25 04:10

alex.bour


1 Answers

CASE can compute any value, even a boolean value as returned by a comparison. In SQLite, 1 is the same as "true":

...
AND %d >= (wines.year + wines.maturity)
AND CASE WHEN wines.apogee IS NOT NULL
         THEN %d < (wines.year + wines.apogee)
         ELSE 1
    END
...

The same can be done with the ifnull() function:

...
AND %d >= (wines.year + wines.maturity)
AND ifnull(%d < (wines.year + wines.apogee), 1)
...
like image 65
CL. Avatar answered Oct 30 '25 14:10

CL.