Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an index speed the calculation of a DATEDIFF of two datetime values?

I have a table with three columns:

id | start_date | end_date

I have a view that shows id and DATEDIFF(hour, start_date, end_date):

id | timespan

Will putting an index on the date columns speed that query? Does this only work with DATEADD? If so, why? My understanding is that for arithmetic queries like this, a TABLE SCAN is required.

like image 322
Codeman Avatar asked Nov 29 '25 20:11

Codeman


1 Answers

No. It does not.

You can create a computed column and create an index on that:

alter table <table> add duration as datediff(hour, start_date, end_date);

create index on <table>(duration);

Of course, the index will be most useful if duration is used in where clause, an on clause, or order by.

like image 63
Gordon Linoff Avatar answered Dec 02 '25 15:12

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!