Skip to main content

MySQL Unique Constraints

Introduction

When designing databases, ensuring data integrity is a crucial aspect of the development process. One way to maintain data integrity in MySQL is by using constraints. A unique constraint is a rule that prevents duplicate values from being inserted into specific columns of a table.

Unique constraints are similar to primary keys but with some key differences. While primary keys must also be unique, unique constraints allow NULL values (usually only once), and a table can have multiple unique constraints, but only one primary key.

In this tutorial, we'll explore how to create, modify, and remove unique constraints in MySQL tables, along with practical examples to demonstrate their use cases.

Understanding Unique Constraints

What is a Unique Constraint?

A unique constraint ensures that all values in a column or a set of columns are distinct from one another. This means no two rows in a table can have the same values for the columns defined in the unique constraint.

Why Use Unique Constraints?

  1. Data Integrity: Prevents duplicate entries in columns where values must be unique
  2. Business Rules Implementation: Enforces business-specific rules (e.g., unique email addresses)
  3. Performance: MySQL creates an index on uniquely constrained columns, improving query performance

Creating Tables with Unique Constraints

Single Column Unique Constraint

Let's start by creating a table with a unique constraint on a single column:

sql
CREATE TABLE employees (
employee_id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(100) UNIQUE,
first_name VARCHAR(50),
last_name VARCHAR(50)
);

In this example, the email column has a unique constraint, ensuring no two employees can have the same email address.

Multi-Column Unique Constraint

Sometimes, you need uniqueness across a combination of columns:

sql
CREATE TABLE course_enrollment (
enrollment_id INT AUTO_INCREMENT PRIMARY KEY,
student_id INT,
course_id INT,
enrollment_date DATE,
UNIQUE KEY student_course (student_id, course_id)
);

Here, the combination of student_id and course_id must be unique, meaning a student cannot enroll in the same course twice.

Named Unique Constraint

You can also give your unique constraints meaningful names:

sql
CREATE TABLE products (
product_id INT AUTO_INCREMENT PRIMARY KEY,
sku VARCHAR(20),
product_name VARCHAR(100),
CONSTRAINT unique_sku UNIQUE (sku)
);

Naming constraints makes it easier to reference them later for modifications or when errors occur.

Adding Unique Constraints to Existing Tables

If you already have a table and want to add a unique constraint:

sql
ALTER TABLE customers
ADD CONSTRAINT unique_email UNIQUE (email);

To add a multi-column unique constraint:

sql
ALTER TABLE order_items
ADD CONSTRAINT unique_order_product UNIQUE (order_id, product_id);

Testing Unique Constraints

Let's see what happens when we try to insert duplicate values:

sql
-- First, let's create and populate our table
CREATE TABLE users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE,
email VARCHAR(100) UNIQUE
);

-- Insert first user (will succeed)
INSERT INTO users (username, email) VALUES ('john_doe', '[email protected]');

-- Try to insert another user with the same username (will fail)
INSERT INTO users (username, email) VALUES ('john_doe', '[email protected]');

The second insert will fail with an error similar to:

ERROR 1062 (23000): Duplicate entry 'john_doe' for key 'users.username'

This demonstrates how the unique constraint prevents duplicate usernames.

Unique Constraints vs. Primary Keys

FeatureUnique ConstraintPrimary Key
NULL valuesCan contain one NULL value (in most cases)Cannot contain NULL values
Multiple per tableA table can have multiple unique constraintsOnly one primary key per table
Auto-creates indexYesYes
Identifies recordsNot necessarilyYes, identifies each record

NULL Values in Unique Constraints

An interesting aspect of unique constraints is their handling of NULL values:

sql
-- Create a table to demonstrate NULL handling
CREATE TABLE subscribers (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(100) UNIQUE,
phone VARCHAR(20) UNIQUE
);

-- Insert a record with NULL phone
INSERT INTO subscribers (email, phone) VALUES ('[email protected]', NULL);

-- Insert another record with NULL phone (will succeed in most cases)
INSERT INTO subscribers (email, phone) VALUES ('[email protected]', NULL);

-- Check our results
SELECT * FROM subscribers;

The output would be:

| id | email             | phone |
|----|-------------------|-------|
| 1 | [email protected] | NULL |
| 2 | [email protected] | NULL |

This shows that MySQL allows multiple NULL values in a column with a unique constraint because NULL represents "unknown" and two unknown values aren't considered equal.

Removing Unique Constraints

To remove a unique constraint, you need to use the constraint name or the index name that MySQL created for it:

sql
-- If you know the constraint name
ALTER TABLE products
DROP CONSTRAINT unique_sku;

-- If you know the index name (often the same as column name)
ALTER TABLE employees
DROP INDEX email;

Real-World Example: User Registration System

Let's build a comprehensive example of a user registration system where unique constraints play a crucial role:

sql
-- Create users table with multiple unique constraints
CREATE TABLE users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
phone VARCHAR(20) UNIQUE,
date_registered TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Create user_profiles table with unique external ID
CREATE TABLE user_profiles (
profile_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
social_security VARCHAR(20) UNIQUE,
FOREIGN KEY (user_id) REFERENCES users(user_id)
);

-- Insert some sample data
INSERT INTO users (username, email, phone) VALUES
('alice', '[email protected]', '123-456-7890'),
('bob', '[email protected]', '234-567-8901'),
('charlie', '[email protected]', NULL);

-- Try to insert a duplicate username (will fail)
INSERT INTO users (username, email, phone) VALUES
('alice', '[email protected]', '555-123-4567');

The last insert will fail because 'alice' is already used as a username. This system ensures that:

  1. No two users can have the same username
  2. No two users can have the same email
  3. Phone numbers, if provided, must be unique
  4. Social security numbers in the profiles must be unique

This is exactly how real-world registration systems work to prevent duplicate accounts.

Considerations and Best Practices

  1. Performance Impact: While unique constraints improve data integrity, they add overhead to insert and update operations because MySQL must check existing values.

  2. Case Sensitivity: Be aware that uniqueness checks in MySQL are case-sensitive or case-insensitive depending on your collation settings.

  3. Composite Unique Constraints: Use multi-column unique constraints when individual columns can have duplicates, but their combination must be unique.

  4. Naming Conventions: Always name your constraints explicitly using a consistent naming convention for easier maintenance.

  5. NULL Handling: Remember that multiple NULL values are allowed in unique columns, which may or may not match your business requirements.

Summary

Unique constraints in MySQL are powerful tools for maintaining data integrity by preventing duplicate values in columns or combinations of columns. They help enforce business rules and can improve query performance through automatically created indexes.

In this tutorial, we've covered:

  • Creating tables with single and multi-column unique constraints
  • Adding unique constraints to existing tables
  • Testing unique constraints with practical examples
  • Comparing unique constraints with primary keys
  • NULL value behavior in unique columns
  • Removing unique constraints
  • Real-world application in a user registration system

By properly implementing unique constraints, you ensure your database maintains high data quality and reflects your business rules accurately.

Practice Exercises

  1. Create a books table with a unique ISBN column.
  2. Create an apartments table where the combination of building number, apartment number, and street must be unique.
  3. Add a unique constraint to an existing students table to ensure student IDs are unique.
  4. Create a table that demonstrates the behavior of NULL values in unique constraints.
  5. Implement a simple inventory system where product codes must be unique.

Additional Resources

By mastering unique constraints, you're taking an important step toward building robust and reliable database applications.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)