In SQL, a Primary Key is a fundamental concept used to uniquely identify each record in a table. Every table should have a primary key to enforce data integrity and establish relationships between different tables in a relational database.
A Primary Key in SQL is a column (or set of columns) that uniquely identifies each row in a table. A primary key must satisfy the following requirements:
Primary keys play a crucial role in relational databases. Here’s why they’re essential:
The most common way to set a primary key is on a single column. This is often used for tables where a single attribute can uniquely identify each record, like EmployeeID or CustomerID.
CREATE TABLE table_name (
column_name data_type PRIMARY KEY,
other_column data_type,
...
);
Let’s create a Users table where UserID serves as the primary key.
CREATE TABLE Users (
UserID INT PRIMARY KEY,
Username VARCHAR(50),
Email VARCHAR(100)
);
UserID column is defined as the primary key, ensuring that each UserID is unique and non-null.
INSERT INTO Users (UserID, Username, Email) VALUES (1, 'Alice', 'alice@example.com');
This entry is added successfully.
INSERT INTO Users (UserID, Username, Email) VALUES (1, 'Bob', 'bob@example.com');
-- Error: Duplicate entry '1' for key 'PRIMARY'
This throws an error because UserID 1 already exists.
A Composite Primary Key is a primary key that consists of multiple columns. It’s used when a combination of columns must be unique rather than a single column alone.
CREATE TABLE table_name (
column1 data_type,
column2 data_type,
...
PRIMARY KEY (column1, column2)
);
Suppose we have an OrderDetails table where each OrderID and ProductID pair should be unique.
CREATE TABLE OrderDetails (
OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID)
);
OrderID and ProductID serves as the primary key, so each product can appear only once per order.
INSERT INTO OrderDetails (OrderID, ProductID, Quantity) VALUES (101, 1, 5);
This is successful.
INSERT INTO OrderDetails (OrderID, ProductID, Quantity) VALUES (101, 1, 10);
-- Error: Duplicate entry for composite key 'OrderID-ProductID'
This insertion is blocked as the combination OrderID = 101 and ProductID = 1 already exists.
While both unique constraints and primary keys enforce uniqueness, there are key differences:
NULL values.NULL value (except in some database systems like Oracle).Auto-increment is often used with primary keys to automatically generate unique values for each record, typically in tables where an integer serves as the primary key.
CREATE TABLE table_name (
column_name INT PRIMARY KEY AUTO_INCREMENT,
other_column data_type,
...
);
Let’s create a Products table where ProductID auto-increments with each new product.
CREATE TABLE Products (
ProductID INT PRIMARY KEY AUTO_INCREMENT,
ProductName VARCHAR(50),
Price DECIMAL(10, 2)
);
ProductID automatically increments by 1.
INSERT INTO Products (ProductName, Price) VALUES ('Laptop', 899.99);
INSERT INTO Products (ProductName, Price) VALUES ('Smartphone', 499.99);
ProductID = 1 to ‘Laptop.’ProductID = 2 to ‘Smartphone.’To add a primary key to an existing table, use the ALTER TABLE command.
ALTER TABLE table_name
ADD PRIMARY KEY (column_name);
Assume we want to add a primary key on CustomerID in the Customers table.
ALTER TABLE Customers
ADD PRIMARY KEY (CustomerID);
To remove a primary key:
ALTER TABLE table_name
DROP PRIMARY KEY;
Here are some best practices to keep in mind when setting primary keys:
UserID), known as a surrogate key, rather than using business-specific data.Let’s create two related tables using primary keys and foreign keys.
CREATE TABLE Authors (
AuthorID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100)
);
CREATE TABLE Books (
BookID INT PRIMARY KEY AUTO_INCREMENT,
Title VARCHAR(100),
AuthorID INT,
FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID)
);
Authors table has AuthorID as the primary key.Books table has BookID as the primary key and a foreign key reference to AuthorID in Authors.
INSERT INTO Authors (Name) VALUES ('J.K. Rowling');
INSERT INTO Books (Title, AuthorID) VALUES ('Harry Potter and the Sorcerer''s Stone', 1);
This creates a relationship where the book is linked to its author through the AuthorID.
Primary keys are essential for building structured, relational databases. They provide unique identification for each record, enforce data integrity, and enable relationships across tables. By following best practices and understanding different approaches to primary keys, you can create robust database structures that ensure data accuracy and consistency. Happy Coding!❤️
