ALTER TABLE table_name ADD CONSTRAINT cst_name UNIQUE (col_name);
ALTER TABLE table_name ADD CONSTRAINT cst_name UNIQUE (col1, col2); -- Multiple
ALTER TABLE table_name ADD col_name NUMBER UNIQUE; -- New field
This constraint ensures all values in a column are unique.
Example 1 (MySQL): Adds a unique constraint to the id column when
creating a new users table.
CREATE TABLE users (
id int NOT NULL,
name varchar(255) NOT NULL,
UNIQUE (id)
);
Example 2 (MySQL): Alters an existing column to add a UNIQUE
constraint.
ALTER TABLE users
ADD UNIQUE (id);
CREATE TABLE order_details
( order_detail_id integer CONSTRAINT order_details_pk PRIMARY KEY,
order_id integer NOT NULL,
order_date date,
quantity integer,
notes varchar(200),
CONSTRAINT order_unique UNIQUE (order_id)
);
CREATE TABLE Colleges (
college_id INT NOT NULL UNIQUE,
college_code VARCHAR(20) UNIQUE,
college_name VARCHAR(50)
);