Clustered index on temp table

David George picture David George · Oct 5, 2011 · Viewed 13.3k times · Source

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?

Answer

Peter Henell picture Peter Henell · Oct 4, 2017

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