A PRIMARY KEY
is a column (or a combination of columns) in a table that uniquely identifies each row in that table. Each table can have only one primary key, and the values in this key must be unique and cannot be NULL.
The basic syntax for defining a primary key is as follows:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
...
PRIMARY KEY (column_name)
);
Here’s an example of creating a table with a primary key:
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50)
);
This ensures that the StudentID
field is unique for each student.
A composite primary key is a primary key that consists of two or more columns. This is useful for uniquely identifying a record when a single column is not sufficient.
CREATE TABLE Enrollment (
StudentID INT,
CourseID INT,
PRIMARY KEY (StudentID, CourseID)
);
If you need to add a primary key to an existing table, you can use the following command:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column_name);
For example:
ALTER TABLE Users
ADD CONSTRAINT pk_userid PRIMARY KEY (UserID);
When using the PRIMARY KEY
constraint, keep in mind: