← Back to Glossary

UNIQUE constraint

A UNIQUE constraint ensures that all values in a column, or combination of columns, are distinct across every row in a table.

Overview

A UNIQUE constraint prevents duplicate values from being inserted into a column or set of columns. It's commonly used for things like email addresses, usernames, or external identifiers where duplicates would indicate a data error, even though the column isn't the table's primary key.

UNIQUE vs. PRIMARY KEY

A table can have only one PRIMARY KEY, and primary key columns implicitly disallow NULL. A table can have any number of UNIQUE constraints, and unlike primary keys, most databases (following the SQL standard) treat NULL as unequal to any other value — including another NULL — so multiple NULLs are typically allowed in a UNIQUE column.

Composite Uniqueness

UNIQUE can also apply across a combination of columns, so that the combination must be distinct even if individual columns repeat:

Copy code

CREATE TABLE enrollments ( student_id INTEGER, course_id INTEGER, UNIQUE (student_id, course_id) );

DuckDB Support

DuckDB supports UNIQUE constraints on a single column or a combination of columns:

Copy code

CREATE TABLE users ( id INTEGER PRIMARY KEY, email VARCHAR UNIQUE );

Under the hood, DuckDB automatically builds an Adaptive Radix Tree (ART) index for any column with a PRIMARY KEY or UNIQUE constraint, which is also what makes point lookups on that column fast in addition to enforcing uniqueness.

Related terms

FAQS

Following standard SQL semantics, a UNIQUE constraint permits multiple NULL values, since NULL is never considered equal to another NULL.

Yes, in DuckDB a UNIQUE (or PRIMARY KEY) constraint automatically creates an Adaptive Radix Tree (ART) index on the constrained column(s).