SQL PRIMARY KEY Examples
Let’s look at some examples of the PRIMARY KEY Constraint in SQL, and understand it’s working.
Create PRIMARY KEY in SQL Example
In this example, we will create primary key in a new table using CREATE TABLE statement.
Query
CREATE TABLE Persons (
PersonID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
Verify SQL Primary key creation
To verify if the primary key has been successfully created, we will try adding duplicate values in primary key column, and SQL should return an error.
Query
INSERT INTO Persons VALUES
(1,"Thakur", "Aditya", 22),
(1, "Kumar", "Shubham", 21);
Output
Error: UNIQUE constraint failed: Persons.PersonID
Add PRIMARY KEY to a Table Example
In this example, we will add primary key to a already existing table using ALTER TABLE command.
Let’s consider previous table, and create it without primary key this time.
CREATE TABLE Persons (
PersonID int,
LastName varchar(255) NOT NULL,
FirstName varchar(255), Age int);
This query will add primary key to ‘Persons’ table
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (PersonID);
SQL PRIMARY KEY Constraint
SQL PRIMARY KEY constraint uniquely identifies each record in a database table.