HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Switch VARCHAR to DATE in MySQL

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
switchmysqlvarchardate

Problem

I inherited a database that has a VARCHAR column that really should be a DATE. There's no checking on the form (I need to fix that) so dates constantly get entered as 2016-12-4 instead of 2016-12-04 and so forth.

I'm pretty sure there are historically a lot of bad dates, so I'm a little skeevy about just changing the data type to DATE, but I'm curious about what would be a good strategy for changing that?

Background: (I'm a front-end developer, not a DBA, so while I can get around in SQL I don't know what I don't know and I'm always afraid I'll make a mistake that corrupts the database).

Solution

Use str_to_date() to handle the conversion.

str_to_date('2016-12-4', '%Y-%m-%d');

Code Snippets

str_to_date('2016-12-4', '%Y-%m-%d');

Context

StackExchange Database Administrators Q#159069, answer score: 6

Revisions (0)

No revisions yet.