Estimated reading time: 2 minutes
In SQL, a unique key is a constraint that ensures that the values in a column or set of columns are unique across all rows in a table and that the values cannot be null.
A unique key is similar to a primary key, but it differs in that it does not necessarily need to be the primary way to identify rows in a table.
Here are some key features of a unique key:
- A unique key can be defined on one or more columns in a table, and it can be a single column or a combination of columns.
- Each column in a unique key must contain unique values across all rows in the table, but the key as a whole can contain duplicate null values.
- Unlike a primary key, a unique key does not necessarily need to be the primary way to identify rows in a table, although it can be used for this purpose if desired.
Here’s an example of how to create a unique key on a table:
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(255) UNIQUE
);
In this example, the customers
table has a unique key constraint on the email
column, which ensures that each email address in the table is unique.
This means that no two rows in the table can have the same email address. Note that the primary key constraint is defined on the customer_id
column, which means that this column is used as the primary way to identify rows in the table.