Search code examples
sqlfirebird

SQL firebird YTD except current month


I'm trying to get the dates of year to date excluding the current month.

I tried the method bellow but it is very slow.

SELECT MYDATE FROM TB WHERE

(EXTRACT(YEAR FROM (MYDATE))=EXTRACT(YEAR FROM (CURRENT_DATE)) AND 
                                 EXTRACT(MONTH FROM (MYDATE))<EXTRACT(MONTH FROM (MYDATE)))

Is there a faster method to get the same result?


Solution

  • Update 2024-12-26 (for fb >= 4)

    As pointed out by Mark Rotteveel in the comments, Firebird 4 introduced FIRST_DAY() and LAST_DAY() functions for this purpose. E.g.:

    ...
    WHERE mydate BETWEEN FIRST_DAY(of year from CURRENT_DATE)
                         AND
                         LAST_DAY(of month from DATEADD(-1 month to CURRENT_DATE))
    

    Original Answer (for fb < 4)

    -- Pull every "mydate" between Jan 1 of this year and the last day of
    -- the previous month, inclusive
    SELECT mydate
      FROM tb
     WHERE mydate BETWEEN (
                  CAST(EXTRACT(YEAR FROM CURRENT_DATE) || '-01-01' AS DATE)
                  AND
                  DATEADD(DAY, -EXTRACT(DAY FROM CURRENT_DATE), CURRENT_DATE);
    

    The above will perform the boundary computation once (for the WHERE clause), whereas your initial query would convert/EXTRACT on every row of the table. In theory, the above is faster. In practice, unless you have a huge number of rows and pathologically bad database conditions, I doubt you'll notice a difference.