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
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
SELECT DISTINCT col1, col2, ....
FROM table_name;
SELECT col1, MIN(col2)
FROM table_name
GROUP BY col1;
DISTINCT
- select distinct * from employees; ==> retrieves any row if it has at
least a single unique column.
- select distinct first_name from employees; ==> retrieves unique names
from table. (removes duplicates)
- select distinct count(*) from employees; retrieve number of unique rows
if any row has at least a single unique data.
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)
);