Search code examples
sqldatabasedatewhere-clause

Put two different dates in where statement


I would like to query the data of two specific months in a SQl statement. These are December from last year and January from this year. This needs to be done in the where part of the SQL statement. (example Dec. 22 and Jan. 23)
Currently I am trying it like this:

...
SELECT month, year, [...] from table 
WHERE other condition
AND year IN ('2022', '2023')
AND month IN ('12', '1')
...

But with this I'm getting the December and January data from 2022 and 2023.
How can I solve this that I get just the January data from 2023 and the December data from 2022?


Solution

  • To get January 2023 and December 2022:

    SELECT month, year, [...] from table 
    WHERE other condition
      AND (year = '2023' and month = '1'
        OR year = '2022' and month = '12')
    

    Or, if supported:

    SELECT month, year, [...] from table 
    WHERE other condition
      AND (year, month) IN (('2023', '1'), ('2022', '12'))