What is a unique key in SQL?

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

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

  1. Uniqueness:
    • Each value in the unique key column(s) must be unique. No two rows can have the same value in these columns.
  2. Nullable:
    • Unlike primary keys, unique keys can accept NULL values (depending on the SQL dialect and database system). However, the behavior regarding NULLs can vary:
      • In some systems, multiple NULL values are allowed in unique key columns.
      • In others, only a single NULL is permitted.
  3. 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

FeaturePrimary KeyUnique Key
UniquenessEnforces uniquenessEnforces uniqueness
NullabilityCannot contain NULL valuesCan contain NULL values (varies)
Number per TableOnly one primary key per tableMultiple unique keys per table
PurposeUniquely identifies each rowEnsures 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 and SocialSecurityNumber 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.

TAGS
Coding Interview
System Design Interview
CONTRIBUTOR
Design Gurus Team

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
How to use the Math.pow() method in Java?
What is API in ReactJS?
What should I say in a coding interview?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
Grokking Advanced Coding Patterns for Interviews
Master advanced coding patterns for interviews: Unlock the key to acing MAANG-level coding questions.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2024 Designgurus, Inc. All rights reserved.