Question

I have a table with a InTime and an OutTime column.

Normally when I insert data into this table I set the InTime to a DateTime and the OutTime to null. When the data is removed a OutTime value is set.

When I’m getting data out for a particular time I use something like:

where InTime < sometime and OutTime is > sometime or OutTime is null

My question is, in terms of getting better query / index performance should I be putting some value into OutTime like the max datetime and make the field not nullable?

Then my query becomes

where InTime < sometime and OutTime is > sometime
Was it helpful?

Solution

Leave the field NULL. Don't use OR, use UNION ALL:

select ... from ... where InTime < sometime and OutTime is > sometime 
union all
select ... from ... where InTime < sometime and OutTime is null

Using magic values instead of NULL is a recipe for disaster. At the least, it uses more storage. More specifically, it breaks the semantics of NULL when enforcing database constraints, when computing aggregates and in applications.

Using OR in queries is asking for performance trouble. The optmizer will likely turn any index range seeks into scans. Using UNION is usually better, as the optimizer will create two plans, one optimal for the NULLs one otpimal for the non-NULL, and union them.

If you do not have any index on Intime and/or OutTime then the query will be a scan anyway and the UNION will perform worse than an OR, but then that is not a scenario that is worth talking about. The question is, of course, how to optimize a query on properly designed storage.

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