Primary keys help us identify each row in a table uniquely. Uniqueness ensures no two rows have the same key, so we can find data easily and avoid confusion.
Primary keys and uniqueness in SQL
CREATE TABLE table_name ( column_name datatype PRIMARY KEY, other_column datatype, ... ); -- Or add UNIQUE constraint ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column_name);
The PRIMARY KEY column must have unique values and cannot be NULL.
The UNIQUE constraint also enforces uniqueness but allows NULL values.
CREATE TABLE Users ( UserID INT PRIMARY KEY, UserName VARCHAR(50) );
CREATE TABLE Products ( ProductCode VARCHAR(20) UNIQUE, ProductName VARCHAR(100) );
ALTER TABLE Employees ADD CONSTRAINT unique_email UNIQUE (Email);
This example creates a Customers table with CustomerID as the primary key and Email as a unique column. It inserts two customers successfully. Attempts to insert duplicate CustomerID or Email will fail.
CREATE TABLE Customers ( CustomerID INT PRIMARY KEY, Email VARCHAR(100) UNIQUE, Name VARCHAR(100) ); INSERT INTO Customers (CustomerID, Email, Name) VALUES (1, 'alice@example.com', 'Alice'); INSERT INTO Customers (CustomerID, Email, Name) VALUES (2, 'bob@example.com', 'Bob'); -- This will fail because CustomerID 1 already exists -- INSERT INTO Customers (CustomerID, Email, Name) VALUES (1, 'charlie@example.com', 'Charlie'); -- This will fail because Email 'alice@example.com' already exists -- INSERT INTO Customers (CustomerID, Email, Name) VALUES (3, 'alice@example.com', 'Alice2'); SELECT * FROM Customers;
Primary key columns are automatically unique and cannot be NULL.
Unique constraints allow NULL values.
Trying to insert duplicate values in primary key or unique columns causes errors.
Use primary keys to identify rows and unique constraints to prevent duplicates in other important columns.
Primary keys uniquely identify each row and cannot be NULL.
Unique constraints ensure no duplicate values in a column but allow NULL values.
Both help keep data clean and easy to find.