Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime2 vs DateTime in SQL Server

Which one:

  • datetime
  • datetime2

is the recommended way to store date and time in SQL Server 2008+?

I'm aware of differences in precision (and storage space probably), but ignoring those for now, is there a best practice document on when to use what, or maybe we should just use datetime2 only?

like image 419
Mikeon Avatar asked Aug 26 '09 11:08

Mikeon


People also ask

What is the difference between datetime and DATETIME2 SQL?

Both DateTime and Datetime2 in SQL Server are data types mainly used to define data as well as time details. The datetime2 is an expansion of the existing DateTime type with a longer date range, higher default fractional precision, and a new feature of user-specified precision.

What is DATETIME2 SQL?

The DateTime2 is an SQL Server data type, that stores both date & time together. The time is based on the 24 hours clock. The DateTime2 stores the fractional seconds Up to 7 decimal places (1⁄10000000 of a second). The Precision is optional and you can specify it while defining the DateTime2 column.

Should I use DATETIME2 or Datetimeoffset?

If you are storing only UTC values (where the offset is always zero), you can save storage space with datetime2 . datetimeoffset requires 10 bytes of storage whereas datetime needs 8 bytes for precision 5 or greater, 7 bytes for precision 3-4, and 6 bytes for precision 2 or less.


2 Answers

DATETIME2 has a date range of "0001 / 01 / 01" through "9999 / 12 / 31" while the DATETIME type only supports year 1753-9999.

Also, if you need to, DATETIME2 can be more precise in terms of time; DATETIME is limited to 3 1/3 milliseconds, while DATETIME2 can be accurate down to 100ns.

Both types map to System.DateTime in .NET - no difference there.

If you have the choice, I would recommend using DATETIME2 whenever possible. I don't see any benefits using DATETIME (except for backward compatibility) - you'll have less trouble (with dates being out of range and hassle like that).

Plus: if you only need the date (without time part), use DATE - it's just as good as DATETIME2 and saves you space, too! :-) Same goes for time only - use TIME. That's what these types are there for!

like image 36
marc_s Avatar answered Oct 11 '22 18:10

marc_s


The MSDN documentation for datetime recommends using datetime2. Here is their recommendation:

Use the time, date, datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time, datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications.

datetime2 has larger date range, a larger default fractional precision, and optional user-specified precision. Also depending on the user-specified precision it may use less storage.

like image 169
Adam Porad Avatar answered Oct 11 '22 18:10

Adam Porad