What is a unique key in SQL?
A unique key in SQL is a constraint that ensures all values in a specific column or a combination of columns are distinct across all rows in a table. This constraint helps maintain data integrity by preventing duplicate entries in the designated fields. Unique keys are essential for ensuring that each record can be uniquely identified based on certain attributes, aside from the primary key.
Key Characteristics of a Unique Key
- Uniqueness:
- Each value in the unique key column(s) must be unique. No two rows can have the same value in these columns.
- Nullable:
- Unlike primary keys, unique keys can accept
NULL
values (depending on the SQL dialect and database system). However, the behavior regardingNULL
s can vary:- In some systems, multiple
NULL
values are allowed in unique key columns. - In others, only a single
NULL
is permitted.
- In some systems, multiple
- Unlike primary keys, unique keys can accept
- Multiple Unique Keys:
- A table can have multiple unique keys, allowing different sets of columns to enforce uniqueness independently.
Difference Between Unique Key and Primary Key
Feature | Primary Key | Unique Key |
---|---|---|
Uniqueness | Enforces uniqueness | Enforces uniqueness |
Nullability | Cannot contain NULL values | Can contain NULL values (varies) |
Number per Table | Only one primary key per table | Multiple unique keys per table |
Purpose | Uniquely identifies each row | Ensures distinctiveness of specific columns |
When to Use a Unique Key
-
Natural Keys:
When a column naturally contains unique values (e.g., email addresses, social security numbers), a unique key can enforce this uniqueness without introducing an artificial primary key. -
Alternate Keys:
These are candidate keys that were not selected as the primary key but still require uniqueness. -
Composite Unique Keys:
When uniqueness must be enforced across a combination of columns rather than a single column.
Creating a Unique Key
You can define a unique key when creating a table or by altering an existing table.
1. During Table Creation:
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, Email VARCHAR(100) UNIQUE, PhoneNumber VARCHAR(15), SocialSecurityNumber VARCHAR(11) UNIQUE );
In this example:
Email
andSocialSecurityNumber
are unique keys ensuring no two employees can have the same email or SSN.
2. Adding a Unique Key to an Existing Table:
ALTER TABLE Employees ADD CONSTRAINT UC_Email UNIQUE (Email);
Here, a unique constraint named UC_Email
is added to the Email
column.
3. Composite Unique Key:
CREATE TABLE Orders ( OrderID INT PRIMARY KEY, ProductID INT, CustomerID INT, OrderDate DATE, UNIQUE (ProductID, CustomerID) );
This ensures that each combination of ProductID
and CustomerID
in the Orders
table is unique, preventing the same customer from ordering the same product more than once on the same date.
Practical Example
Consider a Users
table where each user must have a unique username and email address:
CREATE TABLE Users ( UserID INT PRIMARY KEY, Username VARCHAR(50) UNIQUE, Email VARCHAR(100) UNIQUE, PasswordHash VARCHAR(255) );
- Username: Ensures that no two users can have the same username.
- Email: Ensures that each email address is associated with only one user.
Handling Unique Key Violations
When inserting or updating data, if a unique key constraint is violated (i.e., attempting to insert a duplicate value), the DBMS will throw an error and reject the operation. To handle such scenarios gracefully, you can use error handling mechanisms or conditional statements.
Example: Using INSERT IGNORE
in MySQL:
INSERT IGNORE INTO Users (Username, Email, PasswordHash) VALUES ('john_doe', 'john@example.com', 'hashed_password');
If the Username
or Email
already exists, the INSERT
operation will be ignored without causing an error.
Example: Using ON CONFLICT
in PostgreSQL:
INSERT INTO Users (Username, Email, PasswordHash) VALUES ('john_doe', 'john@example.com', 'hashed_password') ON CONFLICT (Email) DO NOTHING;
This will attempt to insert the new user but do nothing if the Email
already exists.
Benefits of Using Unique Keys
-
Data Integrity:
Ensures that specific columns contain unique values, maintaining the accuracy and reliability of the data. -
Optimized Searches:
Unique keys often create indexes automatically, which can speed up query performance when searching based on those columns. -
Preventing Duplicate Records:
Helps in avoiding accidental duplication of important data, such as user accounts or transaction records.
Conclusion
A unique key in SQL is a vital constraint that enforces the uniqueness of values in one or more columns within a table, thereby ensuring data integrity and preventing duplication. Unlike primary keys, unique keys allow NULL
values (depending on the database system) and a table can have multiple unique keys. Understanding how to effectively use unique keys is essential for designing robust and reliable database schemas.
By implementing unique keys appropriately, you can ensure that critical data remains consistent and that your database operates efficiently, making it a fundamental aspect of database design and management.
GET YOUR FREE
Coding Questions Catalog