Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
While a table can have only one Primary Key, real-world entities frequently possess multiple attributes that must be unique across the entire database. For example, in a user registration system, every user has an auto-incremented user_id (Primary Key), but their email address, username, and phone number must also be strictly unique. This is enforced using UNIQUE Constraints.
A UNIQUE constraint guarantees that all values in a column (or group of columns) are distinct. If an INSERT or UPDATE statement attempts to store a duplicate value, MySQL halts the transaction with error 1062 (Duplicate entry).
| Feature | Primary Key | UNIQUE Constraint |
|---|---|---|
| Quantity Allowed | Strictly 1 per table. | Multiple allowed per table. |
| Allows NULL? | Never (NOT NULL is strictly enforced). | Yes! (A UNIQUE column can contain NULL unless explicitly declared NOT NULL). |
| Index Created | Automatically creates a Clustered Index in InnoDB. | Automatically creates a Secondary Unique B-Tree Index. |
| Purpose | Primary row identifier for table organization and foreign keys. | Guarantees business uniqueness across secondary attributes. |
NULL Exception in Unique ConstraintsIn MySQL InnoDB, multiple rows can store NULL in a UNIQUE column without violating the constraint! Because each NULL mathematically represents an unknown value, one unknown is never considered equal to another unknown.
In relational database theory, any column (or set of columns) capable of uniquely identifying a row is called a Candidate Key:
UNIQUE constraints.A Composite UNIQUE Constraint enforces uniqueness across the combination of multiple columns:
CONSTRAINT uq_table_column UNIQUE (col) rather than inline UNIQUE. Naming your constraints makes debugging production error logs and dropping constraints via migrations straightforward.UNIQUE constraint creates an underlying B-Tree index. While this speeds up lookups, unnecessary unique indexes add write overhead on INSERT and UPDATE operations.NULL in a column with a UNIQUE constraint (assuming it is not marked NOT NULL)?uq_email from a table named users in MySQL?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| NOT NULL and DEFAULT Constraints | CHECK Constraints in MySQL |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.