views:

179

answers:

2

Should I store it in a single timestamp/datetime field or separate date and time fields? I prefer to store it as a single timestamp field but I need to know when a user didn't enter a time portion.

How to best store this in the database? I'm using postgresql.

Thanks.

+2  A: 

The obvious answer is to use two separate fields; then you can use NULL values.

If you choose to use one field you will need to choose a magic time part that signifies "didn't enter a real time", which has the danger of coinciding with a real time (however unlikely).

Also, if you intend to use the date and time part separately often, then it might also be convenient to use separate fields; otherwise you will often need to use selection functions for extracting the relevant part of a field.

Martijn
I read in many forums which say separate field is a bad idea. The reason I ask is because I worry there may be hidden cons for using separate fields. But from the points you mentions I believe it's the better choice?
sai
+3  A: 

There are definitely reasons why this is a bad idea. There are also reasons why your choices are limited. It's a bad idea because it's a single data item and for the more practical reason that you can't store a timezone if you have two fields.

As mentioned above, nulls are the obvious benefit of using two fields.

You might also want to consider using a single datetime field and storing a flag to indicate whether or not the user entered a time. This could be a boolean flag. However, you will still need to think about how you are going to use this data - entering only a date into a datetime field will lead to a time component being set to midnight. This will have implications in sorting and selection. Additionally, if you are storing timezones, you will have to be very careful when you use the data.

In order to fulfill your requirement of knowing whether or not a time was entered you will need to have two fields. You do not need the second field to be a time though.

Nic Gibson
Interesting, if I were to use a single timestamp field with timezone information and a boolean to store the data, what do you mean by I will have to be very careful when I use the data?
sai
Apologies for the long delay - you will need to always be careful because your data will contains timestamps set to some date at midnight in some timezone. These will be the dates when the user didn't enter a time. Sorts and comparisons will treat this as midnight not null (and in cross-timezone comparisons this may lead to two times being viewed as differing when you actually just have two dates). You will just have to remain aware of that issue.
Nic Gibson