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!
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.
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'.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With