How do I extract Month and Year in a MySQL date and compare them?

MysqlSqlDate

Mysql Problem Overview


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.

Mysql Solutions


Solution 1 - Mysql

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';

Solution 2 - Mysql

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;

Solution 3 - Mysql

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';

Solution 4 - Mysql

SELECT * FROM Table_name Where Month(date)='10' && YEAR(date)='2016';

Solution 5 - Mysql

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?

Solution 6 - Mysql

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnSmithView Question on Stackoverflow
Solution 1 - MysqlbetasuxView Answer on Stackoverflow
Solution 2 - Mysqlさりげない告白View Answer on Stackoverflow
Solution 3 - MysqlQuestion OverflowView Answer on Stackoverflow
Solution 4 - MysqlWaseem AhmadView Answer on Stackoverflow
Solution 5 - MysqlCarthView Answer on Stackoverflow
Solution 6 - MysqlaibView Answer on Stackoverflow