When to use VARCHAR and DATE/DATETIME

前端 未结 5 1605
野趣味
野趣味 2020-11-29 00:40

We had this programming discussion on Freenode and this question came up when I was trying to use a VARCHAR(255) to store a Date Variable in this format: D/MM/YYYY. So the q

5条回答
  •  青春惊慌失措
    2020-11-29 01:04

    I'd vote for using the date/datetime types, just for the sake of simplicity/consistency.

    If you do store it as a character string, store it in ISO 8601 format:

    • http://www.iso.org/iso/date_and_time_format
    • http://xml.coverpages.org/ISO-FDIS-8601.pdf
    • http://www.cl.cam.ac.uk/~mgk25/iso-time.html

    Among other things, ISO 8601 date/time string (A) collate properly, (B) are human readable, (C) are locale-indepedent, and (D) are readily convertable to other formats. To crib from the ISO blurb, ISO 8601 strings offer

    representations for the following:

    • Date
    • Time of the day
    • Coordinated universal time (UTC)
    • Local time with offset to UTC
    • Date and time
    • Time intervals
    • Recurring time intervals

    Representations can be in one of two formats: a basic format that has a minimal number of characters and an extended format that adds characters to enhance human readability. For example, the third of January 2003 can be represented as either 20030103 or 2003-01-03.

    [and]

    offer the following advantages over many of the locally used representations:

    • Easily readable and writeable by systems
    • Easily comparable and sortable
    • Language independent
    • Larger units are written in front of smaller units
    • For most representations the notation is short and of constant length

    One last thing: If all you need to do is store a date, then storing it in the ISO 8601 short form YYYYMMDD in a char(8) column takes no more storage than a datetime value (and you don't need to worry about the 3 millisecond gap between the last tick of the one day and the first tick of the next. But that's a matter for another discussion. If you break it up into 3 columns — YYYY char(4), MM char(2), DD char(2) you'll use up the same amount of storage, and get more options for indexing. Even better, store the fields as a short for yyyy (4 bytes), and a tinyint for each of MM and DD — now you're down to 6 bytes for the date. The drawback, of course, to decomposing the date components into their constituent parts is that conversion to proper date/time data types is complicated.

提交回复
热议问题