简体   繁体   中英

Why Oracle does not permit you to create both a primary key and unique constraint with the same columns?

Trying to understand Constraints. This article says

Oracle does not permit you to create both a primary key and unique constraint with the same columns.

Followed by an example:

CREATE TABLE supplier
( supplier_id numeric(10) NOT NULL,
  supplier_name varchar2(50) NOT NULL,
  contact_name varchar2(50),
  CONSTRAINT supplier_unique UNIQUE (supplier_id)
);

Do I understand correctly that for this query to work the created supplier_id must not be a primary key?

Also, why is it not allowed? Because Primary Keys are unique by definition and putting a constraint just on that column is meaningless anyway?

Both primary key and unique constraint create an underlying unique index. And since (most of the time) there's no sense in creating twice the same index, Oracle checks and forbids this.

Note about that "most of the time" above: Sometimes it might make sense to have both a B*Tree index and a bitmap index over the same columns. This can be done via function-based indexes, but that's a rather "advanced hack" which comes with a price of making the Oracle query optimizer going slightly nuts about using the "hacked" one.

Do I understand correctly that for this query to work the created supplier_id must not be a primary key?

Yes, in your code example, the supplier_id must not be a primary key in order to allow you to create a unique constraint over the supplier_id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM