Reputation: 28349
I'm curious what the right way is to construct a query where the rows are pulled based on a timestamp that represents a specific month. Given that different months have different numbers of days, is there a way to generate a query that always gives you the rows where the timestamp contains the current month so that the results would only include the current month?
Upvotes: 0
Views: 68
Reputation: 338128
If you have an index on your date field, then this is efficient (T-SQL syntax, the idea applieas to any RDBMS though)
SELECT
*
FROM
tableName
WHERE
dateTimeField
BETWEEN
-- build the string 'YYYY-MM-01', cast back as a datetime
CAST(
CAST(YEAR(GETDATE()) AS varchar) + '-' + CAST(MONTH(GETDATE()) AS varchar) + '-01'
AS datetime
)
AND
-- add one month, subtract one day
DATEADD(mm, 1,
-- build the string 'YYYY-MM-01', cast back as a datetime
CAST(
CAST(YEAR(GETDATE()) AS varchar) + '-' + CAST(MONTH(GETDATE()) AS varchar) + '-01'
AS datetime
)
) - 1
Of course any other method to get two datetime values in the right range would work.
SQL Server has LEFT(CONVERT(varchar, GETDATE(), 120), 8) + '01'
to convert a datetime to string, other Db servers have their own functions to do the same. Maybe you can calculate the two values in the calling application more easily - how you get them, is not the point.
The point is that BETWEEN
can use an index, whereas the other solutions that work with WHERE MONTH(dateTimeField) = 6
will trigger a table scan, which is about the slowest operation you can do on a table.
Upvotes: 0
Reputation: 659
You're looking for something like this:
SELECT * FROM table where MONTH(date_row) = $month;
Upvotes: 0
Reputation: 2200
Try this sql.
select *
from yourtable
where yourdatefield>=DATE_SUB(CURDATE(),INTERVAL 1 MONTH);
Upvotes: 0
Reputation:
Just use MONTH
:
select *
from foo
where month_column = MONTH(getdate())
and year_column = YEAR(getdate())
Upvotes: 0
Reputation: 11171
Do you mean something like this
SELECT * FROM tbl WHERE
MONTH(timesp) = MONTH(NOW()) AND
YEAR(timesp) = YEAR(NOW());
Upvotes: 2
Reputation: 9302
You can use the FROM_UNIXTIME()
function:
SELECT *
FROM tableName
WHERE MONTH(FROM_UNIXTIME(timestampField))==6
Upvotes: 1