Skip to main content

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 Name field 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 TABLE can be used to make an existing column unique.

Notes:

  • UNIQUE allows 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, UNIQUE guarantees that a column's value won't repeat within the table.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.