Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add composite primary key to table

create table d(id numeric(1), code varchar(2)) 

After I create the above table how can I add a composite primary key on both fields and also a foreign key?

like image 378
Domnic Avatar asked Aug 29 '09 09:08

Domnic


People also ask

How do you create a composite primary key in a table?

A Composite Primary Key is created by combining two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined, but it does not guarantee uniqueness when taken individually, or it can also be understood as a primary key created by combining two or more ...

How do I add a composite primary key in access?

To select more than one field to create a composite key, hold down CTRL and then click the row selector for each field. On the Design tab, in the Tools group, click Primary Key. A key indicator is added to the left of the field or fields that you specify as the primary key.

Can a primary key be composite?

Primary keys must contain unique values. A primary key column cannot have NULL values. A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key.


2 Answers

In Oracle, you could do this:

create table D (   ID numeric(1),   CODE varchar(2),   constraint PK_D primary key (ID, CODE) ); 
like image 115
Simon Nickerson Avatar answered Sep 21 '22 23:09

Simon Nickerson


alter table d add constraint pkc_Name primary key (id, code)

should do it. There's lots of options to a basic primary key/index depending on what DB your working with.

like image 41
Chris W Avatar answered Sep 19 '22 23:09

Chris W