1

I have the following SQL code below. It is taking forever to complete but if I run just the SELECT DISTINCT ID, ParentID FROM Y WHERE ID IN (3,4), it completes instantly.

DECLARE @table TABLE
(
  ID int,
  ParentID int
)

INSERT INTO @table 
SELECT DISTINCT ID, ParentID FROM Y WHERE ID IN (3,4)

SELECT * FROM @table

What is going on, this makes no sense.

3
  • 3
    Post the query plans for both versions. Commented Nov 8, 2012 at 1:39
  • Just how many rows are we talking about here?
    – marc_s
    Commented Nov 8, 2012 at 6:00
  • 1
    A limitation of queries that insert into table variables is that they can't use parallel plans. Commented Jan 18, 2013 at 17:28

3 Answers 3

2

Try to use a temporary table instead. The table variable is optimized for one row only and assumes that is what it will be getting.

Read more here

1
  • 1
    The solution of using a temporary table might work. The explanation that this is because "the table variable is optimized for one row only" is nonsense. Any difference in insert performance between the two will be because of parallel vs serial plans. Commented Jan 18, 2013 at 17:29
1

Even though it is a simple SELECT that will execute almost instantly, if you have a large dataset, the IN will take much longer because it's going to collect all of the data before processing the conditions. Use and EXISTS in it's place and it will most likely run much faster.

1
  • Does the whole thing (including the final SELECT *) take that long? You need to take that out and isolate it to verify that it is the INSERT not the fnial SELECT that is taking that long.
    – Nick.Mc
    Commented Nov 8, 2012 at 3:31
1

There can be multiple reasons for this behaviour. Without execution plan we can only guess the reason, and can't be sure of the exact reason.

  1. Since you are using DISTINCT ID in the query, I assume that ID is not the primary key. Can you modify your query to use PK in the WHERE clause.

  2. It might be possible that the data in the table Y is too large, of the order of several millions, and due to lack if indexing(on the table) & Exists(in the query), query will take a long time.

  3. Try this code just to check the speed

    SELECT DISTINCT ID, ParentID
    FROM Y WHERE ID IN (3,4)
    

Not the answer you're looking for? Browse other questions tagged or ask your own question.