Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query on large table using DateTime WHERE clause

I'm attempting to query data from a rather large table, approximately 98 million rows, using datetime columns in the WHERE clause. It takes approximately 12 minutes to complete - which is obviously not acceptable. The query is simple:

SELECT ID, DateTime1, DateTime2, Value1, Value2
FROM dataTable
WHERE DateTime1 >= '2017-05-15 09:00' AND
      DateTime1 <= '2017-05-15 09:30'

The table has the following structure:

Column Name | DataType
-------------------------
ID          | float
DateTime1   | datetime
DateTime2   | datetime
Value1      | float
Value2      | varchar(20)

The table has the following index:

Nonclustered: DateTime1, DateTime2, ID, Value2
like image 429
Callum Luke Vernon Avatar asked May 03 '26 14:05

Callum Luke Vernon


1 Answers

In SQL Server:

Your index does not cover Value1, so it has to retrieve that column from the table for each row if it is using your existing index.

You could create an covering index (includes all columns required by the query) like so:

create nonclustered index ix_dataTable_DateTime1_cover 
  on dbo.dataTable (DateTime1)
    include (Id, DateTime2, Value1, Value2);

or modify your existing index to include Value1.

Also, check the execution plan. If still have performance issues, share your execution plans using Paste The Plan @ brentozar.com here are the instructions: How to Use Paste the Plan.

like image 108
SqlZim Avatar answered May 06 '26 05:05

SqlZim



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!