Quantcast
Channel: Forum SQL Server Database Engine
Viewing all articles
Browse latest Browse all 15889

Just how well does SQL Server use a three-field clustered PK?

$
0
0

We have a little utility table, "little" with about 100k rows, that has a PK with three fields, then half a dozen other fields.  This morning at 4AM two ETL jobs managed to deadlock over it.  We can't figure out why.

Say the table is something like below, and the data is more or less evenly distributed across 50 states and 10 cities per state, and the names are (magically) unique within a state and city - but not by themselves.

Well, the one job was working on Alabama and the other job was working on Washington, so just how the heck did they manage to start fighting over a page?

The execution plan suggests a second index on just state and city, including name.  What?  It changes the execution plan from using a clustered index scan, when there is only the PK, to using an index seek.  So, SQL Server isn't smart enough or capable of doing a seek on a three-key index, using just the first two fields????????

So the update was doing a clustered index scan, while the insert was doing a clustered index insert, that these both managed to be two-phase operations that were just lucky enough to deadlock each other?

Thanks,

Josh

create table mytable
(
	pkstate		varchar(255) not null,
	pkcity		varchar(255) not null,
	pkname		varchar(255) not null, -- assume these are unique within state/city
	myweight	varchar(255)
);
alter table mytable
add constraint pk_mytable primary key clustered (pkstate,pkcity,pkname);
go
--- this creates a deadlock:
update mytable
  set myweight = t.myweight
from mytable m
  inner join nametable t on m.pkname = t.name
where m.pkstate = @thisstate and m.pkcity = @thiscity;
go
--- deadlocking with:
INSERT mytable
(pkstate,pkcity,pkname,create_date)
SELECT DISTINCT
pkstate,@mycity,pkname,GETDATE()
FROM #temp_export;
go



Viewing all articles
Browse latest Browse all 15889

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>