MySQL Type for Storing a Year: Smallint or Varchar or Date?

前端 未结 3 741
春和景丽
春和景丽 2021-01-07 19:29

I will be storing a year in a MySQL table: Is it better to store this as a smallint or varchar? I figure that since it\'s not a full date, that the date format shouldn\'t

相关标签:
3条回答
  • 2021-01-07 19:44

    My own experience is with Oracle, which does not have a YEAR data type, but I have always tried to avoid using numeric data types for elements just because they are comprised only of digits. (So this includes phone numbers, social security numbers, zip codes as well, as additional examples).

    My own rule of thumb is to consider what the data is used for. If you will perform mathematical operations on it then store it as a number. If you will perform string functions (eg. "Take the last four characters of the SSN" or "Display the phone number as (XXX) XXX-XXXX") then it's a string.

    An additional clue is the requirement to store leading zeroes as part of the number.

    Furthermore, and despite being commonly referred to as a phone "number", they frequently contain letters to indicate the presence of an extension number as a suffix. Similarly, a Standard Book Number potentially ended in an "X" as a "check digit", and an International Standard Serial Number can end with an "X" (despite the ISSN International Centre repeatedly referring to it as an 8-digit code http://www.issn.org/understanding-the-issn/what-is-an-issn/).

    Formatting of phone numbers in an international context is tricky, or course, and conforming to E.164 requires that country calling codes are prefixed with a "+".

    0 讨论(0)
  • 2021-01-07 19:57

    I'd go for small-int - as far as I know - varchar would take more space as well as date. second option would be the date.

    0 讨论(0)
  • 2021-01-07 20:03

    I would use the YEAR(4) column type... but only if the years expected are within the range 1901 and 2155... otherwise, see Gambrinus's answer.

    0 讨论(0)
提交回复
热议问题