🧷 SQL Constraints & Indexes
Estimated reading: 2 minutes 85 views

πŸ”‘ SQL PRIMARY KEY – Uniquely Identify Each Row

🧲 Introduction – What is SQL PRIMARY KEY?

The PRIMARY KEY constraint in SQL ensures that each row in a table can be uniquely identified. It combines UNIQUE and NOT NULL, making it a fundamental element of relational database design.

🎯 In this guide, you’ll learn:

  • How to declare a PRIMARY KEY on one or more columns
  • Differences from UNIQUE constraints
  • Indexing, enforcement, and real-world examples

βœ… 1. Basic PRIMARY KEY Syntax

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

βœ… Ensures each id is unique and never NULL.


🧱 2. Composite PRIMARY KEY

CREATE TABLE enrollments (
  student_id INT,
  course_id INT,
  PRIMARY KEY (student_id, course_id)
);

βœ… Enforces uniqueness across multiple columns.


🧩 3. Add PRIMARY KEY with ALTER TABLE

ALTER TABLE customers
ADD CONSTRAINT pk_customer_id PRIMARY KEY (id);

βœ… Adds a named primary key constraint after creation.


βš™οΈ 4. Behavior & Rules

  • Only one PRIMARY KEY per table
  • Cannot contain NULL values
  • Automatically creates a unique index
  • Composite keys combine multiple fields for uniqueness

πŸ†š 5. PRIMARY KEY vs UNIQUE

FeaturePRIMARY KEYUNIQUE Constraint
Allows NULLs❌ Noβœ… Yes (1+ allowed)
Max per table1Many allowed
Implies indexβœ… Yesβœ… Yes

πŸ“˜ Best Practices

βœ… Recommended❌ Avoid This
Always define a primary key for each tableUsing duplicate or NULL primary values
Use meaningful, minimal fields (e.g., ID)Using large text or composite keys unnecessarily
Name constraints clearlyLetting DBMS assign default names

πŸ“Œ Summary – Recap & Next Steps

The PRIMARY KEY is the cornerstone of relational integrity. It guarantees row uniqueness, enabling joins, lookups, and indexing.

πŸ” Key Takeaways:

  • Ensures every row has a unique, non-null identifier
  • Automatically indexed
  • One per tableβ€”can be single or multi-column

βš™οΈ Real-World Relevance:
Used in user IDs, order numbers, reference IDs, and lookup joins across all database models.

➑️ Next: Learn FOREIGN KEY to relate tables, or explore UNIQUE and NOT NULL combinations.


❓ FAQ – SQL PRIMARY KEY

❓ Can a table have two PRIMARY KEYs?

❌ No. Only one per table, but it can span multiple columns.

❓ Does PRIMARY KEY imply UNIQUE?

βœ… Yes. It’s a combination of UNIQUE + NOT NULL.

❓ Can I change a PRIMARY KEY?

βœ… Yes. You must drop it first, then add a new one.

❓ Is PRIMARY KEY always indexed?

βœ… Yes. Indexing is automatic for primary keys.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ”‘ SQL PRIMARY KEY

Or Copy Link

CONTENTS
Scroll to Top