Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can SQL table have multiple columns with primary key? [duplicate]

Tags:

sql

Can SQL table have multiple columns with primary key?

like image 497
Gal Avatar asked Nov 17 '09 17:11

Gal


People also ask

Can a primary key in SQL have 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 a primary key be setup on multiple columns?

PRIMARY KEY can't have null values. A table can have only one PRIMARY KEY either on one column or multiple columns. When multiple columns are defined as PRIMARY KEY, then, it is called COMPOSITE KEY.

How many columns can a primary key have?

Usually, a primary key is just a single column that uniquely identifies a row within a table. However, a composite primary key consisting of 2 or more columns can be created.

Does SQL allow duplication of the primary key?

Answer: No it is not possible. The wording Primary Key imply non duplicate values, it is by design ! You can have duplicate values in Non Primary Key, it is the only way.


2 Answers

A table can have just one primary key constraint, but that may be comprised of several columns e.g.

create table my_table (col1 integer, col2 integer, col3 integer,    primary key (col1, col2, col3)    ); 

In addition to the primary key, a table may also have one or more UNIQUE constraints, e.g.

create table my_table2 (col1 integer, col2 integer, col3 integer,    primary key (col1, col2),    unique (col2, col3)    ); 
like image 144
Tony Andrews Avatar answered Oct 06 '22 03:10

Tony Andrews


If you mean "can a primary key in SQL have multiple columns", the answer is yes.

like image 37
Stu Avatar answered Oct 06 '22 05:10

Stu