Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL query executing slowly (for some parameter values)
    primarykey
    data
    text
    <p>I have a SQL Server 2005 database with several tables. One of the tables is used to store timestamps and message counters for several devices, and has the following columns:</p> <pre><code>CREATE TABLE [dbo].[Timestamps] ( [Id] [uniqueidentifier] NOT NULL, [MessageCounter] [bigint] NULL, [TimeReceived] [bigint] NULL, [DeviceTime] [bigint] NULL, [DeviceId] [int] NULL ) </code></pre> <p><code>Id</code> is the unique primary key (Guid.Comb), and I have indexes on both <code>DeviceId</code> and <code>MessageCounter</code> columns.</p> <p>What I want to do is find the last inserted row (the row with the largest <code>MessageCounter</code>) for a certain device.</p> <p>The thing that is strange is that a query for <strong>device no. 4</strong> (and all other devices except no.1) returns almost instantaneously:</p> <pre><code>select top 1 * from "Timestamps" where DeviceId = 4 order by MessageCounter desc </code></pre> <p>but the same query for <strong>device no. 1</strong> takes forever to complete:</p> <pre><code>select top 1 * from "Timestamps" where DeviceId = 1 /* this is the only line changed */ order by MessageCounter desc </code></pre> <p>The strangest thing is that device 1 has <strong>much less rows</strong> than device 4:</p> <pre><code>select count(*) from "Timestamps" where DeviceId = 4 (returns 1,839,210) select count(*) from "Timestamps" where DeviceId = 1 (returns 323,276). </code></pre> <p>Does anyone have a clue what I could be doing wrong?</p> <p><strong>[Edit]</strong></p> <p>From the execution plans for both queries, it is clearly visible that Device 1 (lower diagram) creates a much larger number of rows in Index scan:</p> <p><a href="http://img295.imageshack.us/img295/5784/execplans.png" rel="nofollow noreferrer">Execution plans for device 4 (upper) and device 1 (lower) http://img295.imageshack.us/img295/5784/execplans.png</a></p> <p>The difference is when I hover the Index Scan nodes on execution plan diagrams:</p> <pre><code>Device 4 Actual Number of Rows: 1 Device 1 Actual Number of Rows: approx. 6,500,000 </code></pre> <p>6,500,000 rows is a very strange number, since my <code>select count(*)</code> query returns around 300,000 rows for device 1!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload