What is a UNIQUE constraint in SQL?
Instruction: Explain how a UNIQUE constraint protects data integrity, including its treatment of NULL values.
Context: Learn how SQL UNIQUE constraints prevent duplicate values and how they differ from primary keys.
Updated
Example Answer
A UNIQUE constraint prevents duplicate values in a column or combination of columns. I would use it for a business rule that an email address cannot belong to two users. Unlike a primary key, a table can have several UNIQUE constraints. NULL behavior depends on the database, so I check that before relying on it.
Small example
CREATE TABLE users (
user_id INTEGER PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE
);
This rejects duplicate email values. NOT NULL also makes an email mandatory. Case sensitivity depends on the database and column collation; this declaration alone does not guarantee case-insensitive uniqueness.