Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 292
Jeremy L Avatar asked Mar 04 '09 15:03

Jeremy L


People also ask

What is the datatype for year in MySQL?

MySQL displays YEAR values in YYYY format, with a range of 1901 to 2155 , and 0000 . YEAR accepts input values in a variety of formats: As 4-digit strings in the range '1901' to '2155' . As 4-digit numbers in the range 1901 to 2155 .

Can we store date in VARCHAR in MySQL?

There is nothing stopping you putting non-date data in the VARCHAR column in the database. The VARCHAR version is culture specific. You can't easily sort the dates. It is difficult to change the format if you want to later.

Which data type is best to store the date and time?

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'.

Which is better VARCHAR or text in MySQL?

In most circumstances, VARCHAR provides better performance, it's more flexible, and can be fully indexed. If you need to store longer strings, use MEDIUMTEXT or LONGTEXT, but be aware that very large amounts of data can be stored in columns of these types.


2 Answers

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.

like image 82
Powerlord Avatar answered Oct 06 '22 00:10

Powerlord


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.

like image 45
Gambrinus Avatar answered Oct 06 '22 00:10

Gambrinus