MySQL CREATE statement with KEY keyword

MySQLMySQLi Database

As stated in the official docs −

KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(50),
   Age int
);
Query OK, 0 rows affected (0.69 sec)

Following is the query for INDEX, which is a synonym to KEY −

mysql> create index Name_Age_Index on DemoTable(Name,Age);
Query OK, 0 rows affected (0.65 sec)
Records: 0 Duplicates: 0 Warnings: 0

Let us check the description of the table once again −

mysql> desc DemoTable;

This will produce the following output −

+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| Id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| Name  | varchar(50) | YES  | MUL | NULL    |                |
| Age   | int(11)     | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name,Age) values('Robert',21);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Name,Age) values('Bob',23);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Name,Age) values('David',22);
Query OK, 1 row affected (0.39 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------+------+
| Id | Name   | Age  |
+----+--------+------+
|  2 | Bob    | 23   |
|  3 | David  | 22   |
|  1 | Robert | 21   |
+----+--------+------+
3 rows in set (0.00 sec)
raja
Published on 01-Oct-2019 08:55:01
Advertisements