SQL PRIMARY KEY Constraint (With Examples) (2024)

In SQL, the PRIMARY KEY constraint is used to uniquely identify rows. It is a combination of NOT NULL and UNIQUE constraints i.e. it cannot contain duplicate or NULL values.

Example

-- create Colleges table with primary key college_idCREATE TABLE Colleges ( college_id INT, college_code VARCHAR(20) NOT NULL, college_name VARCHAR(50), CONSTRAINT CollegePK PRIMARY KEY (college_id));

Here, the college_id column is the PRIMARY KEY. This means that the values of this column must be unique and it cannot contain NULL values.

Note that the above code works in all major database systems. However, some databases may have a different syntax.

SQL PRIMARY KEY Syntax

The syntax of the SQL PRIMARY KEY constraint is:

CREATE TABLE table_name ( column1 data_type, ..., [CONSTRAINT constraint_name] PRIMARY KEY (column1));

Here,

  • table_name is the name of the table to be created
  • column1 is the name of the column where the PRIMARY KEY constraint is to be defined
  • constraint_name is the arbitrary name given to the constraint
  • [...] signifies that the code inside is optional.

Note: Although naming a constraint using [CONSTRAINT constraint_name] is optional, doing so makes it easier to make changes to and delete the constraint.

Primary Key Error

In SQL, we will get an error If we try to insert NULL or duplicate values in the primary key column.

NOT NULL Constraint Error

We get this error when we supply the primary key with a NULL value. This is because primary keys need to obey the NOT NULL constraint. For example,

-- NOT NULL Constraint Error-- the value of primary key (college_id) is NULLINSERT INTO Colleges(college_id, college_code, college_name)VALUES ("ARD12", "Star Public School");

Here, the SQL command gives us an error because we have supplied a NULL value to the primary key college_id in the Colleges table.

Fix the NOT NULL Constraint Error

-- Insertion Success-- the value of primary key (college_id) is 1INSERT INTO Colleges(college_id, college_code, college_name)VALUES (1, "ARD12", "Star Public School");

Here, the SQL command runs without errors because we have supplied the value 1 to the primary key i.e. college_id.

UNIQUE Constraint Error

We get this error when we supply duplicate values to the primary key, which violates its UNIQUE constraint. For example,

INSERT INTO Colleges(college_id, college_code, college_name)VALUES (1, "ARD12", "Star Public School");-- UNIQUE Constraint Error-- the value of college_id is not uniqueINSERT INTO Colleges(college_id, college_code, college_name)VALUES (1, "ARD12", "Star Public School");

Here, the SQL command gives us an error because we have inserted the duplicate value 1 into the primary key college_id.

Fix the UNIQUE Constraint Error

INSERT INTO Colleges(college_id, college_code, college_name)VALUES (1, "ARD12", "Star Public School");-- Insertion SuccessINSERT INTO Colleges(college_id, college_code, college_name)VALUES (2, "ARD12", "Star Public School");

Here, the SQL command runs without errors because we have supplied unique values 1 and 2 to college_id.

Note: There can only be one primary key in a table. However, that single primary key can contain multiple columns.

Primary Key With Multiple Columns

A primary key may also be made up of multiple columns. For example,

-- add the PRIMARY KEY constraint to multiple columnsCREATE TABLE Colleges ( college_id INT, college_code VARCHAR(20), college_name VARCHAR(50), CONSTRAINT CollegePK PRIMARY KEY (college_id, college_code));

Here, the PRIMARY KEY constraint named CollegePK is made up of the college_id and college_code columns.

This means that the combination of college_id and college_code must be unique and these two columns cannot contain NULL values.

Primary Key Constraint With Alter Table

We can also add the PRIMARY KEY constraint to a column in an existing table using the ALTER TABLE command. For example,

For a Single Column

ALTER TABLE CollegesADD PRIMARY KEY (college_id);

Here, the SQL command adds the PRIMARY KEY constraint to the college_id column in the existing Colleges table.

For Multiple Columns

ALTER TABLE CollegesADD CONSTRAINT CollegePK PRIMARY KEY (college_id, college_code);

Here, the SQL command adds the PRIMARY KEY constraint to the college_id and college_id columns in the existing Colleges table.

Note: This command is not supported by our online SQL editor as it is based on SQLite.

Auto Increment Primary Key

It is a common practice to automatically increase the value of the primary key whenever a new row is inserted. For example,

SQL Server

-- use IDENTITY(x, y) to auto increment the value-- x -> start value, y -> steps to increaseCREATE TABLE Colleges ( college_id INT IDENTITY(1,1), college_code VARCHAR(20) NOT NULL, college_name VARCHAR(50), CONSTRAINT CollegePK PRIMARY KEY (college_id));-- insert record without college_idINSERT INTO Colleges(college_code, college_name)VALUES ("ARD13", "Star Public School");

Oracle

-- create sequence of numbersCREATE SEQUENCE auto_incMINVALUE 1START WITH 1INCREMENT BY 1CACHE 10;CREATE TABLE Colleges ( college_id INT, college_code VARCHAR(20) NOT NULL, college_name VARCHAR(50), CONSTRAINT CollegePK PRIMARY KEY (college_id));-- create trigger before insert to-- add auto incremented valueCREATE TRIGGER auto_inc_triggerBEFORE INSERT ON CollegesFOR EACH ROWBEGINSELECT auto_inc.nextval INTO :new.college_id FROM dualEND;-- insert record without college_idINSERT INTO Colleges(college_code, college_name)VALUES ("ARD13", "Star Public School");

MySQL

-- AUTO_INCREMENT keyword auto increments the valueCREATE TABLE Colleges ( college_id INT AUTO_INCREMENT, college_code VARCHAR(20) NOT NULL, college_name VARCHAR(50), CONSTRAINT CollegePK PRIMARY KEY (college_id));-- insert record without college_idINSERT INTO Colleges(college_code, college_name)VALUES ("ARD13", "Star Public School");

PostgreSQL

-- SERIAL keyword auto increments the valueCREATE TABLE Colleges ( college_id INT SERIAL, college_code VARCHAR(20) NOT NULL, college_name VARCHAR(50), CONSTRAINT CollegePK PRIMARY KEY (college_id));-- insert record without college_idINSERT INTO Colleges(college_code, college_name)VALUES ("ARD13", "Star Public School");

Remove Primary Key Constraint

We can remove the PRIMARY KEY constraint in a table using the DROP clause. For example,

SQL Server, Oracle

ALTER TABLE CollegesDROP CONSTRAINT CollegePK;

MySQL

ALTER TABLE CollegesDROP PRIMARY KEY;

Here, the SQL command removes the PRIMARY KEY constraint from the Colleges table.

Also Read:

  • SQL CREATE TABLE
  • SQL INSERT INTO
  • SQL ALTER TABLE
  • SQL FORIEGN KEY
  • SQL Constraints
SQL PRIMARY KEY Constraint (With Examples) (2024)
Top Articles
The Wealthiest Historical Figures and How Much They Would be Worth in Today’s Dollars | TitleMax
Web2 vs Web3: The Future of the Internet | Mysterium VPN
Using GPT for translation: How to get the best outcomes
4-Hour Private ATV Riding Experience in Adirondacks 2024 on Cool Destinations
Team 1 Elite Club Invite
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Cad Calls Meriden Ct
Xrarse
Crazybowie_15 tit*
Minn Kota Paws
Mivf Mdcalc
Keurig Refillable Pods Walmart
Readyset Ochsner.org
Lenscrafters Huebner Oaks
Learn2Serve Tabc Answers
Stihl Km 131 R Parts Diagram
Inside the life of 17-year-old Charli D'Amelio, the most popular TikTok star in the world who now has her own TV show and clothing line
Pekin Soccer Tournament
Lonesome Valley Barber
Persona 5 Royal Fusion Calculator (Fusion list with guide)
Fsga Golf
Encyclopaedia Metallum - WikiMili, The Best Wikipedia Reader
European Wax Center Toms River Reviews
'Insidious: The Red Door': Release Date, Cast, Trailer, and What to Expect
Pronóstico del tiempo de 10 días para San Josecito, Provincia de San José, Costa Rica - The Weather Channel | weather.com
Duke University Transcript Request
Revelry Room Seattle
Pdx Weather Noaa
What Is The Lineup For Nascar Race Today
Baldur's Gate 3 Dislocated Shoulder
Marine Forecast Sandy Hook To Manasquan Inlet
Texas Baseball Officially Releases 2023 Schedule
Linabelfiore Of
Rogers Centre is getting a $300M reno. Here's what the Blue Jays ballpark will look like | CBC News
Grapes And Hops Festival Jamestown Ny
Hannibal Mo Craigslist Pets
Baywatch 2017 123Movies
Jewish Federation Of Greater Rochester
Hebrew Bible: Torah, Prophets and Writings | My Jewish Learning
Wunderground Orlando
Oppenheimer Showtimes Near B&B Theatres Liberty Cinema 12
Cocorahs South Dakota
Linkbuilding uitbesteden
All Weapon Perks and Status Effects - Conan Exiles | Game...
BCLJ July 19 2019 HTML Shawn Day Andrea Day Butler Pa Divorce
Brown launches digital hub to expand community, career exploration for students, alumni
Child care centers take steps to avoid COVID-19 shutdowns; some require masks for kids
Darkglass Electronics The Exponent 500 Test
Dayton Overdrive
Is My Sister Toxic Quiz
Edict Of Force Poe
Latest Posts
Article information

Author: Carmelo Roob

Last Updated:

Views: 6276

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Carmelo Roob

Birthday: 1995-01-09

Address: Apt. 915 481 Sipes Cliff, New Gonzalobury, CO 80176

Phone: +6773780339780

Job: Sales Executive

Hobby: Gaming, Jogging, Rugby, Video gaming, Handball, Ice skating, Web surfing

Introduction: My name is Carmelo Roob, I am a modern, handsome, delightful, comfortable, attractive, vast, good person who loves writing and wants to share my knowledge and understanding with you.