payling
payling

Reputation: 2514

mysql return rows matching year month

How would I go about doing a query that returns results of all rows that contain dates for current year and month at the time of query.

Timestamps for each row are formated as such: yyyy-mm-dd

I know it probably has something to do with the date function and that I must somehow set a special parameter to make it spit out like such: yyyy-mm-%%.

Setting days to be wild card character would do the trick but I can't seem to figure it out how to do it.

Here is a link to for quick reference to date-time functions in mysql:

http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

Thanks

Upvotes: 1

Views: 7697

Answers (3)

Alexey Sviridov
Alexey Sviridov

Reputation: 3490

select * from someTable where year(myDt) = 2009 and month(myDt) = 9 and day(myDt) = 12

Upvotes: 1

longneck
longneck

Reputation: 12226

you could extract the year and month using a function, but that will not be able to use an index.

if you want scalable performance, you need to do this:

SELECT *
  FROM myTable
 WHERE some_date_column BETWEEN '2009-01-01' AND '2009-01-31'

Upvotes: 5

Eric Petroelje
Eric Petroelje

Reputation: 60508

I think EXTRACT is the function you are looking for:

SELECT * FROM table
WHERE EXTRACT(YEAR_MONTH FROM timestamp_field) = EXTRACT(YEAR_MONTH FROM NOW())

Upvotes: 13

Related Questions