Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't two tables have an index of the same name?

I'm creating indexes on two separate tables in the same DB (PostgreSQL), and I got an error saying that an index already exists. This was true, however, the index existed on a different table. After changing the name, it worked.

I'm wondering why this is the case? Why are databases designed such that two tables can't have the same name of an index?

I found two sources that answer this, although the answers are different. One is for MySQL, the other is for Postgres:

In postgres how do I add index to existing table?

Same index name for two tables

like image 354
zebrainatree Avatar asked Nov 18 '14 15:11

zebrainatree


People also ask

Can two tables have same index name?

All indexes within the Maximo schema must have unique names. On SQL Server only, it is possible to create multiple indexes with the same name on different tables from the back end. This causes the ConfigDB utility to fail with the following error: The same index name is used on different tables in the native database.

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 an index be associated with multiple tables?

Yep, indexed views are the answer. You can join the two tables in a view and create a unique clustered index on the view for the required columns.

Can a database have multiple tables with same name?

Yes, You can create Multiple tables in the same Database.


2 Answers

You can have two indexes of the same name. They just can't be in the same schema. Just like you can have two tables of the same name, but not in the same schema.

sandbox=# create schema test;
CREATE SCHEMA
sandbox=# create table public.a (a_id integer not null);
CREATE TABLE
sandbox=# create table test.a (a_id integer not null);
CREATE TABLE
sandbox=# create index a_idx on public.a (a_id);
CREATE INDEX
sandbox=# create index a_idx on test.a (a_id);
CREATE INDEX

This reflects a decision by the PostgreSQL designers. SQL standards don't deal with creating indexes.

like image 153
Mike Sherrill 'Cat Recall' Avatar answered Nov 15 '22 11:11

Mike Sherrill 'Cat Recall'


Because the index is stored in the table pg_class. Within that table there is a composite key comprised of the index name and the namespace, which is why you cannot have two indexes with the same name belonging to the same namespace.

like image 35
Isaac Meals Avatar answered Nov 15 '22 09:11

Isaac Meals