Hackforge Academy

Category: sql

primary key and unique key in sql

Published on 02 Jun 2026

Explanation

A Primary Key is a column or group of columns that uniquely identifies each row in a table. A table can have only one Primary Key. Primary Key values cannot be NULL and cannot contain duplicate values.

Code:

CREATE TABLE users (
  id INT PRIMARY KEY,
  name VARCHAR(100)
);

Explanation

Use a Primary Key when you need a unique identifier for every record, such as User ID, Employee ID, or Product ID.

Code:

INSERT INTO users (id, name) 
VALUES (1, 'John');

Explanation

A Unique Key ensures that all values in a column are unique. Unlike a Primary Key, a table can have multiple Unique Keys and they can allow NULL values (depending on the database).

Code:

CREATE TABLE users (
  id INT PRIMARY KEY,
  email VARCHAR(100) UNIQUE
);

Explanation

Use a Unique Key for fields that must not have duplicate values, such as Email Address, Phone Number, or Username.

Code:

INSERT INTO users (id, email)
 VALUES (1, 'john@example.com');

Explanation

Primary Key vs Unique Key: Primary Key uniquely identifies records and does not allow NULL values. Unique Key prevents duplicate values but is not the main identifier of the table.

Code:

-- Primary Key: id
-- Unique Key: email
CREATE TABLE users (
  id INT PRIMARY KEY,
  email VARCHAR(100) UNIQUE,
  name VARCHAR(100)
);

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community