3

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 !

alex.bour
  • 2,842
  • 9
  • 40
  • 66

1 Answers1

6

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)
...
CL.
  • 173,858
  • 17
  • 217
  • 259