Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clustered index on temp table

I'm trying to optimize a procedure that has code like the following:

CREATE TABLE #t1 (c1 int, c2 varchar(20), c3(varchar(50)...)

CREATE CLUSTERED INDEX ix_t1 ON #t1(c3) ON [PRIMARY]

I wanted to improve that by moving the CLUSTERED index into the table declaration (more caching friendly), but c3 is not unique so this doesn't work:

CREATE TABLE #t1 (c1 int, c2 varchar(20), c3 varchar(50)..., UNIQUE CLUSTERED (c3))

Is there a way to declare a clustered that is not unique in the temp table declaration?

like image 566
David George Avatar asked Oct 05 '11 15:10

David George


People also ask

Can we create clustered index on temp table?

SQL temp tables support adding clustered and non-clustered indexes after the SQL Server temp table creation and implicitly by defining Primary key constraint or Unique Key constraint during the tables creation, but table variables support only adding such indexes implicitly by defining Primary key constraint or Unique ...

Can we create non clustered index on temp table?

Yes it is possible to create a nonclustered columnstore index on the temp table but not the table variable. This is one more reason, why one should consider using temp tables over table variables.

Can we create indexes on temporary tables in SQL?

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 we index a temp table?

You can define complex indexes on temporary tables, just as if they are permanent tables, for the most part. So if you need to index columns but have duplicate values which prevents you from using UNIQUE , this is the way to go. You do not even have to worry about name collisions on indexes.


2 Answers

Yes, it is possible in SQL Server 2014 and above, Create table on MSDN. From 2014 you can specify the indexes inline with the create table statement.

 if object_id('tempdb..#t1') is not null drop table #t1;

CREATE TABLE #t1 (
    c1 int, 
    c2 varchar(20), 
    c3 varchar(50), 

    index [CIX_c3] CLUSTERED (c3),
    index [IX_c1] nonclustered (c1)
)

insert #t1(c3) values ('a'), ('a'), ('a')

select * from #t1
like image 169
Peter Henell Avatar answered Oct 01 '22 22:10

Peter Henell


No there is not...the existence of the ability to define clustered as an option in table creation is to support declaring primary key and unique column constraints, which themselves create indexes. In other words, CLUSTERED in the CREATE TABLE statement is specifying whether or not the index created by the UNIQUE constraint should be clustered or nonclustered, which is important because a table can only have one clustered index.

like image 41
Wil Avatar answered Oct 01 '22 21:10

Wil