#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
Step 8
3 min read

Primary Key

Learn what Primary Keys are and why every table needs one.

What is a Primary Key?

A Primary Key is a unique ID for each row. Like your student ID or passport number.

Simple rule: No two rows can have the same Primary Key.

How Primary Key Works

Basic Syntax

CREATE TABLE students ( student_id INTEGER PRIMARY KEY, name VARCHAR(100), age INTEGER );

Example 1: Auto-Generated IDs

Let database create IDs automatically:

CREATE TABLE students ( student_id SERIAL PRIMARY KEY, name VARCHAR(100) );

Example 2: Insert with Primary Key

INSERT INTO students (name) VALUES ('John'); -- Gets ID 1 INSERT INTO students (name) VALUES ('Mary'); -- Gets ID 2

Example 3: Find by Primary Key

SELECT * FROM students WHERE student_id = 1;

Primary Key Rules

  1. Must be unique - No duplicates
  2. Cannot be NULL - Must have value
  3. One per table - Only one Primary Key
  4. Never changes - Don't modify it

Try It Below

Use the playground to practice:

  • SELECT * FROM students WHERE student_id = 1;
  • SELECT student_id, name FROM students;

What Comes Next

Next: Learn Foreign Keys to connect tables together.

Finished this topic?

Mark it complete to track your progress and maintain your streak!