Is it compulsory to set PRIMARY KEY for AUTO_INCREMENT value?


Yes, use AUTO_INCREMENT with PRIMARY KEY. Let us first create a table −

mysql> create table DemoTable
(
   EmployeeId int NOT NULL AUTO_INCREMENT,
   EmployeeName varchar(40),
   EmployeeAge int,
   PRIMARY KEY(EmployeeId),
   UNIQUE KEY(EmployeeName,EmployeeAge)
);
Query OK, 0 rows affected (0.96 sec)

Let us check the table description of the table −

mysql> desc DemoTable;

This will produce the following output −

+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| EmployeeId   | int(11)     | NO   | PRI | NULL    | auto_increment |
| EmployeeName | varchar(40) | YES  | MUL | NULL    |                |
| EmployeeAge  | int(11)     | YES  |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+
3 rows in set (0.17 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(EmployeeName,EmployeeAge) values('Chris',25);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(EmployeeName,EmployeeAge) values('Robert',34);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(EmployeeName,EmployeeAge) values('Mike',32);
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
|          1 | Chris        |          25 |
|          3 | Mike         |          32 |
|          2 | Robert       |          34 |
+------------+--------------+-------------+
3 rows in set (0.00 sec)

Updated on: 04-Oct-2019

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements