Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create indexes on a temp table when using SELECT INTO?

Tags:

I am loading data from a CSV file into a temp staging table and this temp table is being queried a lot. I looked at my execution plan and saw that a lot of the time is spent scanning the temp table.

Is there any way to create index on this table when I SELECT INTO it?

SELECT *    
FROM TradeTable.staging.Security s
WHERE (
    s.Identifier IS NOT NULL
    OR s.ConstituentTicker IS NOT NULL
    OR s.CompositeTicker IS NOT NULL
    OR s.CUSIP IS NOT NULL
    OR s.ISIN IS NOT NULL
    OR s.SEDOL IS NOT NULL
    OR s.eSignalTicker IS NOT NULL)

enter image description here

like image 713
Ian R. O'Brien Avatar asked Dec 21 '12 20:12

Ian R. O'Brien


People also ask

Can you create indexes on temporary table?

You can define indexes on temporary tables. In many cases, these indexes can improve the performance of queries that use tempdb. The optimizer uses these indexes just like indexes on ordinary user tables.

Can you add an index to a temp table SQL?

Adding indexes to the SQL temp tables will enhance its performance if the index is chosen correctly, otherwise, it can cause performance degradation.

Can the SELECT into statement be used to create a temp table?

We can use the SELECT INTO TEMP TABLE statement to perform the above tasks in one statement for the temporary tables. In this way, we can copy the source table data into the temporary tables in a quick manner.

How do you create an index in a SELECT statement?

SQL Server CREATE INDEX statement In this syntax: First, specify the name of the index after the CREATE NONCLUSTERED INDEX clause. Note that the NONCLUSTERED keyword is optional. Second, specify the table name on which you want to create the index and a list of columns of that table as the index key columns.


1 Answers

The table created by SELECT INTO is always a heap. If you want a PK/Identity column you can either do as you suggest in the comments

CREATE TABLE #T
(
Id INT IDENTITY(1,1) PRIMARY KEY,
/*Other Columns*/
)

INSERT INTO #T 
SELECT *
FROM TradeTable.staging.Security

Or avoid the explicit CREATE and need to list all columns out with

SELECT TOP (0) IDENTITY(int,1,1) As Id, *
INTO #T
FROM TradeTable.staging.Security

ALTER TABLE #T ADD PRIMARY KEY(Id)

INSERT INTO #T 
SELECT *
FROM TradeTable.staging.Security
like image 79
Martin Smith Avatar answered Oct 19 '22 15:10

Martin Smith