Skip to content
Advertisement

Is it a good idea to set the date in to a varchar in sql?

Later on Im going to count the record for every month in year

Advertisement

Answer

It’s generally better to use stronger data types rather than weaker ones. They help you catch invalid inputs, and they stronger signal to your developers and your future self what the column is meant to hold. VARCHAR can hold basically anything.

If you don’t have a specific reason to make this column a VARCHAR, then I would strongly recommend date.

VARCHARs can also cause optimization problems down the road. Since you plan on counting and doing analysis on this column later, indexing and other features will likely better support you with the stronger casting.

And then there’s the data bloat. With MySQL, if you’re just storing a date, 2021-06-08 is 10 bytes, compared to the date of 4 bytes. A date+time like 2021-06-08 14:03:23 is 19 characters at 1 byte each, while storing it in a datetime will be ~8 bytes (depending). The savings are even bigger if you wind up storing fractional seconds.

If you want to read up more on the options for MySQL as one example, you can find them here: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-types.html

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement