patternsqlMinor
New Index on table cause table to be locked really often
Viewed 0 times
reallynewlockedoftencauseindextable
Problem
Here are my tables :
Tracker position is used to store positions send by car trackers. So I have a lot of insert going on.
And I often need to get the last position known for a tracker.
So here is a query generated by Entity Framework :
```
SELECT
[Limit1].[IdTrackerPosition] AS [IdTrackerPosition],
[Limit1].[TrackerId] AS [TrackerId],
[Limit1].[Position] AS [Position],
[Limit1].[Date] AS [Date],
[Limit1].[Speed] AS [Speed],
[Limit1].[NbSatellites] AS [NbSatellites],
[Limit1].[Direction] AS [Direction],
[Limit1].[HDOP] AS [HDOP]
FROM (SELECT DISTINCT
[Extent1].[TrackerId] AS [TrackerId]
FROM [dbo].[TrackerPositions] AS [Extent1]
WHERE ([Extent1].[Position] IS NOT NULL) AND ([Extent1].[TrackerId] IN (1, 48)) ) AS [Distinct1]
OUTER APPLY (SE
CREATE TABLE [dbo].[Trackers] (
[IdTracker] INT IDENTITY (1, 1) NOT NULL,
[IMEI] NVARCHAR (16) NULL,
[CreationDate] DATETIME NULL,
[SuppressionDate] DATETIME NULL,
[LastUpdateDate] DATETIME NULL,
[BuyDate] DATETIME NOT NULL,
[Status] INT NOT NULL,
[LastTrackerUpdateDate] DATETIME NULL,
[IdLastTrackerPosition] INT NULL,
PRIMARY KEY CLUSTERED ([IdTracker] ASC)
);
CREATE TABLE [dbo].[TrackerPositions] (
[IdTrackerPosition] INT IDENTITY (1, 1) NOT NULL,
[TrackerId] INT NOT NULL,
[Position] [sys].[geography] NULL,
[Date] DATETIME NOT NULL,
[Speed] REAL NULL,
[NbSatellites] TINYINT NULL,
[Direction] REAL NULL,
[HDOP] REAL NULL,
PRIMARY KEY CLUSTERED ([IdTrackerPosition] ASC),
CONSTRAINT [TrackerTrackerPosition] FOREIGN KEY ([TrackerId]) REFERENCES [dbo]. [Trackers] ([IdTracker])
);Tracker position is used to store positions send by car trackers. So I have a lot of insert going on.
And I often need to get the last position known for a tracker.
So here is a query generated by Entity Framework :
```
SELECT
[Limit1].[IdTrackerPosition] AS [IdTrackerPosition],
[Limit1].[TrackerId] AS [TrackerId],
[Limit1].[Position] AS [Position],
[Limit1].[Date] AS [Date],
[Limit1].[Speed] AS [Speed],
[Limit1].[NbSatellites] AS [NbSatellites],
[Limit1].[Direction] AS [Direction],
[Limit1].[HDOP] AS [HDOP]
FROM (SELECT DISTINCT
[Extent1].[TrackerId] AS [TrackerId]
FROM [dbo].[TrackerPositions] AS [Extent1]
WHERE ([Extent1].[Position] IS NOT NULL) AND ([Extent1].[TrackerId] IN (1, 48)) ) AS [Distinct1]
OUTER APPLY (SE
Solution
Your index should be on
But I really don't like the query from EF.
Edit:
...because "most recent" should mean "latest datetime", not "latest identity value"
(TrackerId ASC, [Date] DESC) INCLUDE (Position) so that it can easily locate the most recent one for each Tracker.But I really don't like the query from EF.
Edit:
...because "most recent" should mean "latest datetime", not "latest identity value"
Context
StackExchange Database Administrators Q#86681, answer score: 4
Revisions (0)
No revisions yet.