PostgreSQL Unique Constraints
· 3 min read
In PostgreSQL, a unique constraint ensures that the values in one or more columns of a table are unique across all rows. This means that no two rows in the table can have the same value(s) for the specified column(s). It's a common feature used to enforce data integrity and ensure that duplicate data cannot be stored.
How It Works
- A unique constraint creates an implicit index on the column(s) it is applied to. This index is used to enforce the uniqueness of the values.
- A unique constraint can be defined on a single column or a combination of multiple columns.
Key Characteristics
- Single-Column Uniqueness:
Ensures that no two rows have the same value in a single column.
In this example:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE
);- The
emailcolumn must have unique values.
- The