8๏ธโƒฃ ๐Ÿ›‘ MySQL Constraints & Keys
Estimated reading: 4 minutes 98 views

๐Ÿ” MySQL Keys โ€“ UNIQUE, PRIMARY KEY, FOREIGN KEY Explained


๐Ÿงฒ Introduction โ€“ Why Use Keys in MySQL?

In MySQL, keys are a fundamental part of relational database design. They ensure data uniqueness, row identification, and relationships across tables. Using keys properly allows you to:

  • Prevent duplicate entries (UNIQUE)
  • Identify rows with certainty (PRIMARY KEY)
  • Maintain referential integrity (FOREIGN KEY)

๐ŸŽฏ In this guide, youโ€™ll learn:

  • The role and syntax of PRIMARY KEY, FOREIGN KEY, and UNIQUE
  • How to define and manage keys
  • Real-world use cases and best practices

๐Ÿ”‘ 1. PRIMARY KEY โ€“ Uniquely Identify Rows

A PRIMARY KEY is a column (or set of columns) that uniquely identifies each row in a table.

๐Ÿ”น Syntax

PRIMARY KEY (column1 [, column2])

๐Ÿ”น Example

CREATE TABLE employees (
  emp_id INT PRIMARY KEY,
  name VARCHAR(100)
);

Explanation:

  • emp_id must be unique and not null.
  • Automatically indexed.

๐Ÿ”น Composite Primary Key

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

Explanation:
Prevents a student from enrolling in the same course more than once.


โœ… 2. UNIQUE โ€“ Enforce Column Uniqueness

The UNIQUE constraint ensures that all values in a column (or set of columns) are distinct.

๐Ÿ”น Syntax

UNIQUE (column_name)

๐Ÿ”น Example

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

Explanation:

  • Prevents duplicate emails from being stored.
  • Allows one NULL (depending on configuration).

๐Ÿ”น Multi-Column Unique

UNIQUE (first_name, last_name)

Explanation:
Ensures the same combination of first_name and last_name doesn’t appear more than once.


๐Ÿ”— 3. FOREIGN KEY โ€“ Enforce Relationships

A FOREIGN KEY creates a link between two tables, ensuring that data in the child table matches existing values in the parent table.

๐Ÿ”น Syntax

FOREIGN KEY (child_column) REFERENCES parent_table(parent_column)
[ON DELETE action] [ON UPDATE action]

๐Ÿ”น Example

CREATE TABLE orders (
  order_id INT PRIMARY KEY,
  customer_id INT,
  FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

Explanation:
Ensures you canโ€™t insert an order for a non-existent customer.


๐Ÿ”น With Cascading Actions

FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
ON DELETE CASCADE
ON UPDATE CASCADE
  • ON DELETE CASCADE: Deletes child rows if the parent is deleted.
  • ON UPDATE CASCADE: Updates child keys if the parent changes.

๐Ÿ“‹ Key Differences Summary

Key TypeUniqueNot NullOne per TableRelationships
PRIMARY KEYโœ…โœ…โœ…โŒ
UNIQUEโœ…โŒโŒโŒ
FOREIGN KEYโŒโŒโŒโœ…

๐Ÿงช Add Keys to Existing Tables

๐Ÿ”น Add Primary Key

ALTER TABLE employees ADD PRIMARY KEY (emp_id);

๐Ÿ”น Add Unique Key

ALTER TABLE users ADD UNIQUE (email);

๐Ÿ”น Add Foreign Key

ALTER TABLE orders
ADD CONSTRAINT fk_customer
FOREIGN KEY (customer_id) REFERENCES customers(customer_id);

โš ๏ธ Dropping Keys

๐Ÿ”น Drop Primary Key

ALTER TABLE employees DROP PRIMARY KEY;

๐Ÿ”น Drop Unique Key

ALTER TABLE users DROP INDEX email;

๐Ÿ”น Drop Foreign Key

ALTER TABLE orders DROP FOREIGN KEY fk_customer;

๐Ÿ“˜ Best Practices

โœ… Practice๐Ÿ’ก Reason
Always define PRIMARY KEY on every tableEnsures fast lookup and indexing
Use UNIQUE for critical user inputsPrevents duplication in emails, usernames
Index foreign keysBoosts JOIN performance
Use CASCADE carefullyCan delete or modify lots of data unintentionally
Name constraints explicitly (CONSTRAINT)Easier to drop or alter them later

๐Ÿš€ Real-World Use Cases

Use CaseKey UsedWhy
Identifying each userPRIMARY KEYEnsures every user is uniquely tracked
Prevent duplicate emailsUNIQUEMaintains email integrity
Relating orders to customersFOREIGN KEYEnforces referential integrity
Managing enrollment recordsComposite PKTracks unique student-course pairings

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

MySQL keys are essential to relational data modeling. They ensure each row is unique, searchable, and correctly related to other data. Understanding and applying PRIMARY, UNIQUE, and FOREIGN keys allows you to build robust and scalable schemas.

๐Ÿ” Key Takeaways

  • Use PRIMARY KEY to uniquely identify rows
  • Use UNIQUE to prevent duplicates in critical columns
  • Use FOREIGN KEY to connect related tables safely
  • Cascade actions with care
  • Index keys for performance

โš™๏ธ Real-World Relevance

Keys are foundational in e-commerce, CRM, HR systems, finance, and any relational data system requiring clean, valid, and interconnected records.


โ“ FAQ โ€“ MySQL Keys


โ“ Can I have multiple UNIQUE constraints?

โœ… Yes. You can have multiple UNIQUE constraints on different columns or combinations.


โ“ Can a FOREIGN KEY reference a non-primary column?

โœ… Yes, but the referenced column must have a UNIQUE or PRIMARY KEY constraint.


โ“ Can a PRIMARY KEY be null?

โŒ No. PRIMARY KEY is always NOT NULL.


โ“ How do I create a named constraint?

CONSTRAINT constraint_name UNIQUE (column_name)

โ“ Do FOREIGN KEYS improve performance?

โœ… They improve data integrity, but may add overhead on INSERT/DELETE. Always index both sides for best JOIN performance.


Share Now :
Share

๐Ÿ” MySQL Keys (UNIQUE, PRIMARY KEY, FOREIGN KEY)

Or Copy Link

CONTENTS
Scroll to Top