How do you make a field unique in a row?
To make a field unique, the UNIQUE constraint is used, forbidding repeated values in that column.
Ways to set uniqueness:
1. When creating the table
sql
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL UNIQUE, -- a unique field
Age INT
);- The
Namefield can't repeat within the table.
2. By adding a constraint to an existing table
sql
ALTER TABLE Employees
ADD CONSTRAINT unique_name UNIQUE (Name);ALTER TABLEcan be used to make an existing column unique.
Notes:
UNIQUEallows NULL (in most DBMSs), but repeated non-null values are forbidden.- A combination of several fields can be made unique, e.g.
(Name, Age), so that combination of values doesn't repeat.
Put simply,
UNIQUEguarantees that a column's value won't repeat within the table.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.