0

I have a table that contains a huge amount of data and I want to query it using a date range.

Here's the query

SELECT TOP (10000) 
    [PositionId] AS [PositionId], 
    [DeviceId] AS [DeviceId],     
    [Course] AS [Course], 
    [Latitude] AS [Latitude], 
    [Longitude] AS [Longitude], 
    [Speed] AS [Speed], 
    [MomentTiming] AS [MomentTiming],                             
    [Fuel] AS [Fuel], 
    [Ignition] AS [Ignition]        
 FROM
    [PositionInsights]
 WHERE
    deviceId = 352 
    AND [MomentTiming] >= '8/12/2015 7:38:00 AM' 
    AND [MomentTiming] <= '8/12/2015 3:38:00 PM'

The problem is that this simple query takes too much time, about 35 sec

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

As a general rule, any fields in your where clause should be indexed. And you should make sure the indexes are not fragmented over time if you are doing a lot of CRUD on the table(s). So I would create two separate indexes, one on the deviceid field and another on the MomentTiming field. If your table is in the millions or billions of rows, you will probably want to set up table partitions on one of those fields. If the deviceid field is an autonumber field, then that might be a good enough range partitioning value, otherwise partition on your MomentTiming date field. If you partition, keep the indexes the same as I described.

UPDATE: since you only have millions, not billions, of rows, just start with the indexing and see what happens. However, if your data is growing fast, you may want to look at partitioning anyway. Also, if you go the partitioning route, you should try to put the different files on different mountpoints to get the best performance.

HTH

Mark Giaconia
  • 3,844
  • 5
  • 20
  • 42
  • another thought is that you could store your dates as bigints, since there is a lot of opinion out there that number-based indexes often provide faster lookups – Mark Giaconia Aug 12 '15 at 13:54
  • 3
    datetimes are already a numeric value presented as a datetime. I doubt this would boost performance at all – t-clausen.dk Aug 12 '15 at 13:59