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?
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.
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).
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.
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
).
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