xxxxxxxxxx
CREATE TABLE Colleges (
college_id INT NOT NULL UNIQUE,
college_code VARCHAR(20) UNIQUE,
college_name VARCHAR(50)
);
xxxxxxxxxx
The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);
To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
xxxxxxxxxx
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);
xxxxxxxxxx
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)
);