I want to get the records of last month based on my db table [member] field "date_created".
What's the sql to do this?
For clarification, last month - 1/8/2009 to 31/8/2009
If today is 3/1/2010, I'll need to get the records of 1/12/2009 to 31/12/2009.
The way I fixed similar issue was by adding Month to my SELECT portion
and than I added WHERE statement
Last month consider as till last day of the month. 31/01/2016 here last day of the month would be 31 Jan. which is not similar to last 30 days.
You can get the last month records with this query
and another upgrade to mrdenny's solution.
It gives the exact last day of the previous month as well.
All the existing (working) answers have one of two problems:
1. Ignored Indices:
For the most part, when a column being searched has a function called on it (including implicitly, like for
CAST
), the optimizer must ignore indices on the column and search through every record. Here's a quick example:We're dealing with timestamps, and most RDBMSs tend to store this information as an increasing value of some sort, usually a
long
orBIGINTEGER
count of milli-/nanoseconds. The current time thus looks/is stored like this:You don't see the 'Year' value (
'2014'
) in there, do you? In fact, there's a fair bit of complicated math to translate back and forth. So if you call any of the extraction/date part functions on the searched column, the server has to perform all that math just to figure out if you can include it in the results. On small tables this isn't an issue, but as the percentage of rows selected decreases this becomes a larger and larger drain. Then in this case, you're doing it a second time for asking aboutMONTH
... well, you get the picture.2. Unintended data:
Depending on the particular version of SQL Server, and column datatypes, using
BETWEEN
(or similar inclusive upper-bound ranges:<=
) can result in the wrong data being selected. Essentially, you potentially end up including data from midnight of the "next" day, or excluding some portion of the "current" day's records.What you should be doing:
So we need a way that's safe for our data, and will use indices (if viable). The correct way is then of the form:
Given that there's only one month,
@startOfPreviousMonth
can be easily substituted for/derived by:If you need to derive the start-of-current-month in the server, you can do it via the following:
A quick word of explanation here. The initial
DATEDIFF(...)
will get the difference between the start of the current era (0001-01-01
- AD, CE, whatever), essentially returning a large integer. This is the count of months to the start of the current month. We then add this number to the start of the era, which is at the start of the given month.So your full script could/should look similar to the following:
All date operations are thus only performed once, on one value; the optimizer is free to use indices, and no incorrect data will be included.