Archive for January 2013

Why you need to sanitize database inputs

Finding the previous month using SQL

I needed to find a way to always select the date range of the previous month.

So if it’s January, I need to select rows with dates between Dec 1 and Dec 31 of the previous year.

If it’s February, I need to select dates with Jan 1 and Jan 31 of the previous year.

Here’s how to do it:

select
trunc(trunc(sysdate, ‘MM’) – 1, ‘MM’),
to_char(trunc(trunc(sysdate, ‘MM’) – 1, ‘MM’),’DD-MON-YYYY’) “First Day of Last Month”,
trunc(trunc(sysdate, ‘MM’) – 1),
to_char(trunc(sysdate, ‘MM’) – 1,’DD-MON-YYYY’) “Last Day of Last Month”
from dual ;