I have the following query, its runtime is ~2 seconds until I join ProductStores
on StoreID
which increases it to ~3 minutes, joining only on ProductID keeps it at ~2 seconds.
SELECT
Enabled = pp.PspEnabled
, StockStatusID = ss.ID
, WebSellable = pp.PspWebSellable
, CSSellable = pp.PspCsSellable
FROM
#ExternalProducts pp
JOIN
Product p ON p.ExternalCode = pp.code
JOIN
Stores s ON s.Name = pp.p_externalStore
JOIN
StockStatus ss ON ss.Name = pp.PspStockStatus
JOIN
ProductStores ps ON (/* Store join increases time only */ ps.StoreID = s.ID AND ps.ProductID = p.ID)
Rows:
- Stores: 108
- Product: 136'598
- ProductStores: 609'963
Keys:
CONSTRAINT [PK_dbo.Stores]
PRIMARY KEY CLUSTERED ([ID] ASC)
CONSTRAINT [PK_dbo.Product]
PRIMARY KEY CLUSTERED ([ID] ASC)
CONSTRAINT [PK_dbo.ProductStores]
PRIMARY KEY CLUSTERED ([ProductID] ASC, [StoreID] ASC)
CONSTRAINT [FK_dbo.ProductStores_dbo.Stores_SiteID]
FOREIGN KEY([StoreID]) REFERENCES [dbo].[Stores] ([ID])
CONSTRAINT [FK_dbo.ProductStores_dbo.Product_ProductID]
FOREIGN KEY([ProductID]) REFERENCES [dbo].[Product] ([ID])
Execution Plan:
The execution plan shows the bulk cost is coming from a Hash Match (Inner Join) with a Hash Keys Probe [dbo].[Stores].Name
and Hash Keys Build [#ExternalProducts].p_externalstore
which I assume is the problem but I'm not sure how to interpret this?
Any help is greatly appreciated!