Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does making a primary key in multiple columns generate indexes for all of them?

If I set a primary key in multiple columns in Oracle, do I also need to create the indexes if I need them?

I believe that when you set a primary key on one column, you have it indexed by it; is it the same with multiple column PKs?

Thanks

like image 476
juan Avatar asked Feb 10 '09 12:02

juan


People also ask

Does creating a primary key create an index?

When you create a PRIMARY KEY constraint, a unique clustered index on the column or columns is automatically created if a clustered index on the table does not already exist and you do not specify a unique nonclustered index. The primary key column cannot allow NULL values.

Can primary key be based on multiple columns?

The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).

Can an index be created on multiple columns?

An index can be defined on more than one column of a table. For example, if you have a table of this form: CREATE TABLE test2 ( major int, minor int, name varchar );

Why use multiple columns for a primary key?

Well, a primary key that is made up of 2 or more columns is called a composite primary key. A common real world use case for this is, when you have a many-to-many relationship between two tables i.e when multiple rows in one table are associated with multiple rows in another table.


2 Answers

No, indexes will not be created for the individual fields.

If you have a composit key FieldA, FieldB, FieldC and you

select * from MyTable where FieldA = :a 

or

select * from MyTable where FieldA = :a and FieldB = :b

Then it will use this index (because it they are the first two fields in the key)

If you have

select * from MyTable where FieldB = :b and FieldC = :c

Where you are using parts of the index, but not the full index, the index will be used less efficiently through an index skip scan, full index scan, or fast full index scan.

(Thanks to David Aldridge for the correction)

like image 76
Binary Worrier Avatar answered Oct 15 '22 21:10

Binary Worrier


If you create a primary key on columns (A, B, C) then Oracle will by default create a unique index on (A, B. C). You can tell Oracle to use a different (not necessarily unique) existing index like this:

alter table mytable add constraint mytable_pk 
primary key (a, b, c)
using index mytable_index;
like image 30
Tony Andrews Avatar answered Oct 15 '22 21:10

Tony Andrews