MySQL Constraint
A PRIMARY KEY in MySQL is a constraint that uniquely identifies each row in a table. It guarantees:
NULL.ID, RollNo, AccountNo, etc.Defining a primary key directly on a column inside CREATE TABLE:
-- Define a table with a single-column PRIMARY KEY
CREATE TABLE table_name (
ID INT PRIMARY KEY,
Name VARCHAR(100)
);
Defining a primary key separately (useful for composite keys):
-- Define a table with a composite PRIMARY KEY
CREATE TABLE table_name (
OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID)
);
Here is a simple table where ID uniquely identifies each employee.
-- Create Employees table with PRIMARY KEY on ID
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR(100),
Age INT,
Salary DECIMAL(10,2)
);
ID as PRIMARY KEY – each employee gets a unique ID.ID again will cause an error.ID.Valid inserts:
INSERT INTO Employees VALUES (1, 'Alice', 28, 45000.00);INSERT INTO Employees VALUES (2, 'Bob', 32, 52000.00);If you try:
INSERT INTO Employees VALUES (1, 'Charlie', 30, 48000.00);MySQL will reject it because ID = 1 already exists. This is how the PRIMARY KEY protects your table from duplicate records.
Composite primary keys are handy in junction tables, like when you store which products belong to which order:
-- Each (OrderID, ProductID) pair must be unique
CREATE TABLE OrderItems (
OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID)
);
INT or BIGINT types for primary keys—they are efficient and fast.AUTO_INCREMENT with integer primary keys to generate IDs automatically.Students with StudentID as the primary key and insert some rows.StudentID and observe the error MySQL throws.CourseEnrollment with a composite key on (StudentID, CourseID).