Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a table have multiple Primary keys?

Tags:

I am very confused right now, maybe you can help me to understand the problem better regarding the question that can a table have two primary keys if yes then how ? And if no, then why?

like image 881
Pankaj Kumar Avatar asked Dec 23 '13 11:12

Pankaj Kumar


People also ask

Can a table have 3 primary keys?

A primary key is a field or set of fields with values that are unique throughout a table. Values of the key can be used to refer to entire records, because each record has a different value for the key. Each table can only have one primary key.

Can a table have multiple primary key explain with example?

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. If a table has a primary key defined on any field(s), then you cannot have two records having the same value of that field(s).

Why there is only one primary key in a table?

The major reason is because that is the definition of the primary key. A table can have multiple unique keys that identify each row, but only one primary key. In databases such as MySQL, the primary key is also a clustered index.


1 Answers

You ask if you can have more than one primary key field and you most certainly can. You can have only one primary key, but that can consist of as many columns as you need to uniquely identify your rows.

Use something like this when you are creating your table:

CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)  

where P_Td and LastName are columns in your table.

If you think you want more than one primary key, then the answer is "not really." You can have only one primary key. However, you can have as many indexes as you want that have a unique constraint on them. A unique index does pretty much the same thing as a primary key.

for example :-

CREATE TABLE Persons (    P_Id int NOT NULL,    LastName varchar(255) NOT NULL,    FirstName varchar(255),    Address varchar(255),    City varchar(255),    CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName) ) 

Note: In the example above there is only ONE PRIMARY KEY (pk_PersonID). However, the value of the pk_PersonID is made up of two columns (P_Id and LastName).

like image 114
Diwakar Avatar answered Sep 24 '22 15:09

Diwakar