mysql STR_TO_DATE not working

Thinh Phan picture Thinh Phan · Aug 29, 2014 · Viewed 13.7k times · Source

I have a table with a varchar column called birthday

CREATE TABLE IF NOT EXISTS `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `birthday` varchar(30) COLLATE utf16_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf16 COLLATE=utf16_unicode_ci AUTO_INCREMENT=5 ;

INSERT INTO `test` (`id`, `birthday`) 
VALUES (1, '20041225'),
       (2, '2004-12-25'),
       (3, '19941225'),
       (4, '19941201');

I try to run this query:

SELECT str_to_date(birthday,"%Y%m%d") 
FROM `test` 
WHERE 1

But it always return rows with null values.

If I run the query:

SELECT str_to_date('20141225',"%Y%m%d") 
FROM `test` 
WHERE 1

It will return 2014-12-25

So what wrong with my query?

Answer

scrowler picture scrowler · Aug 29, 2014

Leave it to simpler functions. DATE() returns the date part of a string in YYYY-MM-DD format:

SELECT DATE(birthday) FROM `test`

Result:

2004-12-25      
2004-12-25      
1994-12-25      
1994-12-01      

The reason your code isn't working is that STR_TO_DATE() expects the same input and output formats, e.g. STR_TO_DATE('2014-08-29', '%Y-%m-%d'). Take a look at the examples in the documentation. This function is used mostly to convert dates or times from one format to another, where the original format is something from outside MySQL and you want to import the data into MySQL's date format for example - in this case, you'll know what the original date format is.

Example:

SELECT STR_TO_DATE('20041225', '%Y-%m-$d');   -- null - formats don't match
SELECT STR_TO_DATE('2004-12-25', '%Y-%m-%d'); -- 2004-12-25 - formats match