mysql extract year from date format

Mysql

Mysql Problem Overview


I need a mysql query to extract the year from the following date format from a table in my database.

For eg :

        subdateshow
      ----------------		
        01/17/2009
        01/17/2009
        01/17/2009
        01/17/2009
        01/17/2009

the following query didn't working

select YEAR ( subdateshow ) from table 

The column type is varchar. Is there any way to solve this?

Mysql Solutions


Solution 1 - Mysql

Since your subdateshow is a VARCHAR column instead of the proper DATE, TIMESTAMP or DATETIME column you have to convert the string to date before you can use YEAR on it:

SELECT YEAR(STR_TO_DATE(subdateshow, "%m/%d/%Y")) from table

See http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date

Solution 2 - Mysql

SELECT EXTRACT(YEAR FROM subdateshow) FROM tbl_name;

Solution 3 - Mysql

You can try this:

SELECT EXTRACT(YEAR FROM field) FROM table WHERE id=1

Solution 4 - Mysql

This should work:

SELECT YEAR(STR_TO_DATE(subdateshow, '%m/%d/%Y')) FROM table;

eg:

SELECT YEAR(STR_TO_DATE('01/17/2009', '%m/%d/%Y'));  /* shows "2009" */

Solution 5 - Mysql

try this code:

SELECT DATE_FORMAT(FROM_UNIXTIME(field), '%Y') FROM table

Solution 6 - Mysql

This should work if the date format is consistent:

select SUBSTRING_INDEX( subdateshow,"/",-1 ) from table 

Solution 7 - Mysql

TRY:

SELECT EXTRACT(YEAR FROM (STR_TO_DATE(subdateshow, '%d/%m/%Y')));

Solution 8 - Mysql

try this code:

SELECT YEAR( str_to_date( subdateshow, '%m/%d/%Y' ) ) AS Mydate

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
QuestionRenjith RView Question on Stackoverflow
Solution 1 - MysqlGordonView Answer on Stackoverflow
Solution 2 - MysqlNooNa MarJaView Answer on Stackoverflow
Solution 3 - MysqlJamshid HashimiView Answer on Stackoverflow
Solution 4 - MysqlpglView Answer on Stackoverflow
Solution 5 - Mysqlram4ndView Answer on Stackoverflow
Solution 6 - MysqlemcommentsView Answer on Stackoverflow
Solution 7 - MysqlSudhir BastakotiView Answer on Stackoverflow
Solution 8 - MysqlBoopathiView Answer on Stackoverflow