Search code examples
sql-serverindexingtemp-tables

Temp Table INLINE Indexing UNIQUE CLUSTERED vs NON-UNIQUE NONCLUSTERED, and naming requirements


I find when creating a UNIQUE CLUSTERED index, I do not have to specify a name:

CREATE TABLE [#TEMP01]
(
    [TradeDate] DATE NOT NULL
        UNIQUE CLUSTERED([TradeDate])
);

I presume SQL Server is internally generating a name for the above index.

When I attempt to create a NONUNIQUE/NONCLUSTERED index, I'm compelled to supply a name:

CREATE TABLE [#TEMP02]
(
    [TradeDate] DATE NOT NULL
        INDEX [IX_TradeDate] NONCLUSTERED([TradeDate])
);

Can I create a non-unique inline index without having to supply a name?


Solution

  • No you cannot.

    The grammar for inline indexes defines that you must supply a name

    <column_index> ::=
     INDEX index_name [ CLUSTERED | NONCLUSTERED ]
        [ WITH ( <index_option> [ ,... n ] ) ]
        .....
    

    And for table-level indexes (possibly multi-column):

    <table_index> ::=
    {
        {
          INDEX index_name  [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ]
             ( column_name [ ASC | DESC ] [ ,... n ] )
        | INDEX index_name CLUSTERED COLUMNSTORE
        | INDEX index_name [ NONCLUSTERED ] COLUMNSTORE ( column_name [ ,... n ] )
        }
        [ INCLUDE ( column_name [ ,... n ] ) ]
        ....
    

    What you originally referred to is not a Unique Clustered index, it's a Unique Clustered constraint. Constraints can indeed be defined without supplying a name, although you'd be advised to give it one. The primary difference between these two is that indexes can have INCLUDE columns and WHERE filters, constraints cannot. Both can be used as the target of a foreign key.