I have a SQL Server 2005 database with multiple tables. One of the tables is used to store timestamps and message counters for several devices and has the following columns:
CREATE TABLE [dbo].[Timestamps] (
[Id] [uniqueidentifier] NOT NULL,
[MessageCounter] [bigint] NULL,
[TimeReceived] [bigint] NULL,
[DeviceTime] [bigint] NULL,
[DeviceId] [int] NULL
)
Idis the only primary key (Guid.Comb), and I have indexes for the DeviceIdand columns MessageCounter.
What I want to do is find the last inserted row (the row with the largest MessageCounter) for a specific device.
The strange thing is that the request is for no. 4 (and all other devices except 1) returns almost instantly:
select top 1 *
from "Timestamps"
where DeviceId = 4
order by MessageCounter desc
but same request for device no. 1 runs forever:
select top 1 *
from "Timestamps"
where DeviceId = 1
order by MessageCounter desc
, 1 , 4:
select count(*) from "Timestamps" where DeviceId = 4
(returns 1,839,210)
select count(*) from "Timestamps" where DeviceId = 1
(returns 323,276).
- , ?
[]
, 1 ( ) :
4 () 1 () http://img295.imageshack.us/img295/5784/execplans.png
, :
Device 4 Actual Number of Rows: 1
Device 1 Actual Number of Rows: approx. 6,500,000
6 500 000 - , select count(*) 300 000 1!