Question

I store an amendment date field in a lot of my tables. Sometimes I need to use the time portion for my logic and sometimes I just need the date portion. I'm wondering which of the following scenarios is more efficient/best practice:

  1. Storing two columns - one of type DATE and one of type DATETIME - which both represent the same instance in time but in which the DATE column obviously only stores the date portion. When I need to do a comparison on date only I use the DATE column and when I need to do a comparison which includes the time I use the DATETIME column.

  2. Storing one column of type DATETIME and using CONVERT(DATE, Date_Amended_Col) to retrieve the date portion whenever I need it.

Is there a significant overhead using the CONVERT every time? I think the DATE portion is likely to be the one accessed more often so I feel like I would be using CONVERT a lot.

I can't think of any obvious downsides to the second method apart from the fact that both fields need to be updated rather than just one when an amendment is made and I can always use a trigger for that if I feel the need to.

Or is there a better way? Would using a computed column be the same as using the CONVERT every time?

Any thoughts would be appreciated.

Many thanks,

Al

Was it helpful?

Solution

I would recommend a PERSISTED computed column. See the below definition from Microsoft.

Unless otherwise specified, computed columns are virtual columns that are not physically stored in the table. Their values are recalculated every time they are referenced in a query. The Database Engine uses the PERSISTED keyword in the CREATE TABLE and ALTER TABLE statements to physically store computed columns in the table. Their values are updated when any columns that are part of their calculation change. By marking a computed column as PERSISTED, you can create an index on a computed column that is deterministic but not precise. Additionally, if a computed column references a CLR function, the Database Engine cannot verify whether the function is truly deterministic. In this case, the computed column must be PERSISTED so that indexes can be created on it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top