Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql extract year from date format

Tags:

mysql

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?

like image 260
Renjith R Avatar asked Jan 03 '12 13:01

Renjith R


People also ask

How do I get just the year from a date in SQL?

You can use year() function in sql to get the year from the specified date.

How can get date in dd mm yyyy format in MySQL?

The MySQL DATE_FORMAT() function formats a date value with a given specified format. You may also use MySQL DATE_FORMAT() on datetime values and use some of the formats specified for the TIME_FORMAT() function to format the time value as well.

How do I display month and year in SQL?

There are two SQL function to do it: DATEPART() YEAR() and MONTH().


2 Answers

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

like image 166
Gordon Avatar answered Oct 06 '22 23:10

Gordon


SELECT EXTRACT(YEAR FROM subdateshow) FROM tbl_name; 
like image 45
NooNa MarJa Avatar answered Oct 06 '22 22:10

NooNa MarJa