Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to use string data type for dates in MySQL instead of using datetime data type?

While implementing web applications on top of MySQL database, I'm thinking if it is a good idea to just use string data type to store dates?

For example, I can just store dates as '201110191503999' into database. Also this is convenient to query by date. For example, select * from some_table where the_date like '20111019%'

Is there any performance issue if we use string for dates? and are there any advantages for using date/datetime data type?

Thanks in advance!

like image 690
Jake W Avatar asked Oct 19 '11 07:10

Jake W


People also ask

Should dates be stored as strings?

Is it safe to store dates as a string in mysql? It is safe as long as the format that you use to represent your dates is unambiguous (that is, each value maps to a unique date). But it is always inefficient not to use the proper datatype to store a value.

What is the best data type for date in SQL?

The DATETIME type is used when you need values that contain both date and time information. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.

Should I use the datetime or TIMESTAMP data type in MySQL?

The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts.

Which format is correct for giving a date in MySQL?

Returns the current date and time as a value in ' YYYY-MM-DD hh:mm:ss ' or YYYYMMDDhhmmss format, depending on whether the function is used in string or numeric context.


2 Answers

Always use the column type for what what is needed; if you are using a date, use DATETIME, if it is a timestamp, use TIMESTAMP and so on.

Depending on in what you are coding, all the formatting of the data can be done on the actual page in whatever language you are using.

Also, you can take advantage of MySQL functions such as NOW(), rather than using the language's version and then storing it into the database.

like image 104
nvcode Avatar answered Sep 20 '22 04:09

nvcode


If your data is of date type then store the data in a DATE (or DATETIME if you have a time element to it).

If you store dates as strings then you are asking for trouble! For example, what is to stop somebody writing a value of 'I am not a date' into you string 'date' field? Or what happens if you have '20111019' and '2011-10-19' and want them to be treated as equal? Furthermore you will be missing out on a whole raft of MySQL DATE and TIME specific functions

Never store a date as a string if you can possibly avoid it.

like image 32
Tom Mac Avatar answered Sep 19 '22 04:09

Tom Mac