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
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.
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.
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.
Yes, You can create Multiple tables in the same Database.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With