Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline index definition fails when name is the same as table name

SQL Server objects i.e. tables and indexes have their own namespaces. So it is possible to have the same name for index and table(but it's not a common/good practice):

CREATE TABLE t(id INT PRIMARY KEY, col INT);
CREATE INDEX t ON t(col);

SELECT * FROM sys.tables WHERE name = 't';
SELECT * FROM sys.indexes WHERE name = 't';

db<>fiddle demo

Unfortunately I am not able to create the same construct using inline index definition:

CREATE TABLE t(id INT PRIMARY KEY, col INT, INDEX t(col));

Msg 2714 Level 16 State 5 Line 1

There is already an object named 't' in the database.

-- below code is working correctly
CREATE TABLE t(id INT PRIMARY KEY, col INT, INDEX t1(col));

db<>fiddle demo 2

Do I miss something obvious or is it a bug?

like image 962
Lukasz Szozda Avatar asked Jan 09 '19 21:01

Lukasz Szozda


People also ask

Can index and table have same name?

Index names are specific to each table. You cannot have two indexes of the same name in one table, but you can have many indexes of the same name, one for every table.

Can indexes have the same name?

Because index names must be unique within the table, you cannot create or rename an index to have the same name as an existing PRIMARY KEY or UNIQUE constraint on the table.

Can we create a inline of index with create table?

The new syntax was introduced which allows you to create certain index types inline with the table definition. These could be at column level, concerning just that column, or at the table level, with indexes containing several columns.

Can table variables be indexed?

Creating an index on a table variable can be done implicitly within the declaration of the table variable by defining a primary key and creating unique constraints. The primary key will represent a clustered index, while the unique constraint a non clustered index.


1 Answers

Do I miss something obvious or is it a bug?

Looks like a bug.

CREATE TABLE t(id INT PRIMARY KEY, col INT, INDEX t(col));

outputs

Microsoft SQL Server 2017 (RTM-GDR) (KB4293803) - 14.0.2002.14 (X64) 
    Jul 21 2018 07:47:45 
    Copyright (C) 2017 Microsoft Corporation
    Developer Edition (64-bit) on Windows 10 Enterprise 10.0 <X64> (Build 17763: ) (Hypervisor)


(1 row affected)

Msg 2714, Level 16, State 5, Line 4
There is already an object named 't' in the database.
Msg 1750, Level 16, State 1, Line 4
Could not create constraint or index. See previous errors.

Please add a feedback item here: https://feedback.azure.com/forums/908035-sql-server Especially noting that this is a regression in SQL 2016.

like image 143
David Browne - Microsoft Avatar answered Nov 01 '22 15:11

David Browne - Microsoft