76

How do I extract the month and date from a mySQL date and compare it to another date?

I found this MONTH() but it only gets the month. I looking for month and year.

3
  • 2
    There is a YEAR function too. Oct 20, 2011 at 4:02
  • 2
    @zerkms DATE_FORMAT() worked perfectly. I'd give you the correct answer. Would you mind explaining the difference between %c, %d and %e? %c worked fine but the last 2 gave me an incorrect date.
    – JohnSmith
    Oct 20, 2011 at 4:34
  • 8
    DATE_FORMAT(date,'%Y%m') works as well as EXTRACT(YEAR_MONTH FROM date)
    – Mario
    Feb 11, 2014 at 3:10

6 Answers 6

94

in Mysql Doku: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_extract

SELECT EXTRACT( YEAR_MONTH FROM `date` ) 
FROM `Table` WHERE Condition = 'Condition';
1
  • 12
    Can it please be explained when EXTRACT is preferred versus DATE_FORMAT? Jul 3, 2019 at 14:46
87

While it was discussed in the comments, there isn't an answer containing it yet, so it can be easy to miss. DATE_FORMAT works really well and is flexible to handle many different patterns.

DATE_FORMAT(date,'%Y%m')

To put it in a query:

SELECT DATE_FORMAT(test_date,'%Y%m') AS date FROM test_table;
40

If you are comparing between dates, extract the full date for comparison. If you are comparing the years and months only, use

SELECT YEAR(date) AS 'year', MONTH(date) AS 'month'
 FROM Table Where Condition = 'Condition';
0
11
SELECT * FROM Table_name Where Month(date)='10' && YEAR(date)='2016';
0
1

You may want to check out the mySQL docs in regard to the date functions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

There is a YEAR() function just as there is a MONTH() function. If you're doing a comparison though is there a reason to chop up the date? Are you truly interested in ignoring day based differences and if so is this how you want to do it?

1
  • Im trying to get the month and year for now.
    – JohnSmith
    Oct 20, 2011 at 4:36
1

There should also be a YEAR().

As for comparing, you could compare dates that are the first days of those years and months, or you could convert the year/month pair into a number suitable for comparison (i.e. bigger = later). (Exercise left to the reader. For hints, read about the ISO date format.)

Or you could use multiple comparisons (i.e. years first, then months).

2
  • Dates can be compared without math :-)
    – zerkms
    Oct 20, 2011 at 4:04
  • oh yeah, let me add that too.
    – aib
    Oct 20, 2011 at 4:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.