views:

645

answers:

3

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 be an answer but I'll include that as well.

Smallint? varchar(4)? date? something else?

Examples:

  • 2008

  • 1992

  • 2053

+6  A: 

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.

R. Bemrose
Well I feel silly for having completely missed this type. Thanks
Nerdling
It's not a widely used type. The only advantage it has over the smaller int types is that you can use date functions on it.
R. Bemrose
As it's only one byte wide, it only supports years in range '1901' to '2155'
Paul Dixon
@Paul: That's true... I've noted that in my answer now.
R. Bemrose
@Paul: I'd believe that MySQL would be updated before then to avoid a Y2.155K bug — I hope. Good concern either way.
Nerdling
thanks for mentioning the year-datatype - didn't know that one
Gambrinus
Yeah thanks for the tip - I'd never heard of this one either!
nickf
+4  A: 

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.

Gambrinus
+2  A: 

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.

David Aldridge