How To Specify Unique Constraint For Multiple Columns In MySQL


How to make multiple columns unique (together) in MySQL.

Short Answer

  • For an existing table:
1
ALTER TABLE `tablename` ADD UNIQUE `unique_id` (`column1`, `column2`);

ALTER TABLE is to change the table schema. ADD UNIQUE is to add the unique constraint. Then we can define the new unique key with multiple columns.

  • To create a new table:
1
2
3
4
5
6
CREATE TABLE `tablename` (
  id INTEGER PRIMARY KEY,
  column1 TEXT NOT NULL,
  column2 TEXT NOT NULL,
  UNIQUE KEY `unique_id` (`column1`, `column2`)
);

Example

Suppose we have the following EMPLOYEE table, we would like to make the combination of name and dept unique.

Table EMPLOYEE:

1
2
3
4
5
6
7
+-------+-------+------------+
| empId | name  | dept       |
+-------+-------+------------+
|     1 | Clark | Sales      |
|     2 | Dave  | Accounting |
|     3 | Ava   | Sales      |
+-------+-------+------------+
  • For an existing table, we can do the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
-- create
CREATE TABLE EMPLOYEE (
  empId INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  dept TEXT NOT NULL
);

-- insert
INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales');
INSERT INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting');
INSERT INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales');

ALTER TABLE EMPLOYEE ADD UNIQUE uniq_id (name(255), dept(255));
  • To create a new table with unique key:
1
2
3
4
5
6
7
8
9
10
11
12
-- create
CREATE TABLE EMPLOYEE (
  empId INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  dept TEXT NOT NULL, 
  UNIQUE KEY uniq_id (name(255), dept(255))
);

-- insert
INSERT INTO EMPLOYEE VALUES (0001, 'Clark', 'Sales');
INSERT INTO EMPLOYEE VALUES (0002, 'Dave', 'Accounting');
INSERT INTO EMPLOYEE VALUES (0003, 'Ava', 'Sales');




Related Posts

How To Specify Unique Constraint For Multiple Columns In MySQL

How to make multiple columns unique (together) in an existing...

How To Select One Row Per ID With Max Value On A Column

Suppose we have the following REIMBURSEMENT table, find the max...

How To Get The Size Of A Table In MySQL

How to get the size of a table in MySQL...

How To Get The Size Of A Database In MySQL

How to get the size of a database in MySQL...

How To Concatenate Multiple Rows Into One Field In MySQL

How to concatenate multiple rows into one field in MySQL...

How To Change The Data Type Of A Column In MySQL

Given a table EMPLOYEE, change the data type of the...