Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Selecting a date range that dynamically excludes the current month in SQL

I’m looking to select data with a date range from an arbitrary point, say 2020-01-01 up until -but not including- the beginning of the current month, and allow this to be dynamic so regardless of when the query is run, it excludes values from the current month.

I attempted

SELECT date_column
FROM table
WHERE date_column >= '2020-01-01' and date_column < MONTH(GETDATE())
ORDER BY date_column DESC

but got the following error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

QL compilation error: Can not convert parameter 'EXTRACT(month from GETDATE())' of type [NUMBER(2,0)] into expected type [TIMESTAMP_NTZ(9)]

How do I correct this?

>Solution :

use DATE_TRUNC to truncate the current date to month level value.

SELECT date_column
FROM table
WHERE date_column >= '2020-01-01' and date_column < DATE_TRUNC('MONTH', GETDATE())
ORDER BY date_column DESC

thus:

SELECT date_column
FROM (values 
    ('2022-11-23'::date),
    ('2022-12-23'::date),
    ('2022-10-23'::date)
      t(date_column)
)
WHERE date_column >= '2020-01-01' and date_column < DATE_TRUNC('MONTH', GETDATE())
ORDER BY date_column DESC

gives:

DATE_COLUMN
2022-10-23
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading