π 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 KEYon one or more columns - Differences from
UNIQUEconstraints - 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 KEYper table - Cannot contain NULL values
- Automatically creates a unique index
- Composite keys combine multiple fields for uniqueness
π 5. PRIMARY KEY vs UNIQUE
| Feature | PRIMARY KEY | UNIQUE Constraint |
|---|---|---|
| Allows NULLs | β No | β Yes (1+ allowed) |
| Max per table | 1 | Many allowed |
| Implies index | β Yes | β Yes |
π Best Practices
| β Recommended | β Avoid This |
|---|---|
| Always define a primary key for each table | Using duplicate or NULL primary values |
| Use meaningful, minimal fields (e.g., ID) | Using large text or composite keys unnecessarily |
| Name constraints clearly | Letting 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 :
