Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kind of indexes will help me in this MERGE query?

I have a table like this:

Name | TimeA | TimeB | ValueA | ValueB

And, I am performing some MERGE operations as follows:

  CREATE TABLE #TEMP1...

  INSERT INTO #TEMP1
  SELECT Name, Value
  FROM dbo.AnotherTable
  WHERE ...

  MERGE INTO dbo.MyTable AS Target
    USING (SELECT Name, Value FROM #TEMP1) AS Source
    ON Target.Name = Source.Name
    AND Target.TimeA = @TimeA
  WHEN MATCHED THEN
    UPDATE SET ValueA = Value
  WHEN NOT MATCHED THEN
    INSERT (Name, TimeA, TimeB, ValueA)
    VALUES (Source.Name, @TimeA, @TimeB, Value)

The Query Execution Plan says the following:

MERGE -> Table Merge 3% -> Compute Scalar 0% -> 
Top 0% -> Compute Scalar 0% -> Compute Scalar 0% ->
Nested Loops (Left Outer Join) 0% <- Constant Scan 0%
              ^
              |
              |
              --- Compute Scalar 0% <- Table Spool (Kager Spool) 12% <- Table Scan 86%

The plan, however does not tell me that an index will improve the performance. I'm thinking an unclustered index on (Name,TimeA) should improve performance. Is there a better way to achieve performance for MERGE queries like this?

EDIT 1: I should note the sizes of the tables. On an average Source always contains 30-70 rows on an average and Target contains > 30 million rows.

like image 914
Legend Avatar asked Mar 23 '23 20:03

Legend


1 Answers

I would consider

WHEN MATCHED AND ValueA <> Value THEN

YOu may be updating records that do not need to be.

like image 191
HLGEM Avatar answered Mar 31 '23 18:03

HLGEM