A primary key is a field (or set of fields) in a table that uniquely identifies each row in the table. It is a constraint that ensures that the data in the column is unique and cannot be null.
Here is the syntax for creating a primary key in SQL:
CREATE TABLE table_name (
column_1 datatype PRIMARY KEY,
column_2 datatype,
column_3 datatype,
...
);
For example, if you want to create a table called Students
with a primary key on the StudentID
column, you would use the following SQL statement:
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(255),
LastName VARCHAR(255),
Age INT
);
You can also create a primary key on multiple columns. For example:
CREATE TABLE Orders (
OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID)
);
This creates a primary key on the combination of the OrderID
and ProductID
columns, ensuring that each combination of values in these columns is unique.
It is important to note that a table can only have one primary key, which can consist of one or multiple columns. The primary key is used to uniquely identify each row in the table and is important for maintaining the integrity of the data.