MySQL index on column of int type?

MySQLMySQLi Database

Adding an index on column of int type is a good choice to run your query faster whenever your table has lots of records.

If your table has less records then it is not a good choice to use index on column of int type.

To understand the concept, let us create a table. The query to create a table is as follows −

mysql> create table indexOnIntColumnDemo
   -> (
   -> UserId int,
   -> UserName varchar(20),
   -> UserAge int,
   -> INDEX(UserId)
   -> );
Query OK, 0 rows affected (0.85 sec)

Now check the description of table −

mysql> desc indexOnIntColumnDemo;

Here is the output −

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| UserId   | int(11)     | YES  | MUL | NULL    |       |
| UserName | varchar(20) | YES  |     | NULL    |       |
| UserAge  | int(11)     | YES  |     | NULL    |      |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.04 sec)

Now you can insert some records in the table using insert command. The query is as follows −

mysql> insert into indexOnIntColumnDemo values(1001,'John',23);
Query OK, 1 row affected (0.22 sec)
mysql> insert into indexOnIntColumnDemo values(1002,'Sam',25);
Query OK, 1 row affected (0.14 sec)
mysql> insert into indexOnIntColumnDemo values(1003,'Carol',22);
Query OK, 1 row affected (0.24 sec)
mysql> insert into indexOnIntColumnDemo values(1004,'Mike',26);
Query OK, 1 row affected (0.14 sec)

Now you can display all records from the table using select statement. The query is as follows −

mysql> select *from indexOnIntColumnDemo;

The following is the output −

+--------+----------+---------+
| UserId | UserName | UserAge |
+--------+----------+---------+
| 1001   | John     |      23 |
| 1002   | Sam      |      25 |
| 1003   | Carol    |      22 |
| 1004   | Mike     |      26 |
+--------+----------+---------+
4 rows in set (0.00 sec)

To run it faster, use the condition on index column of int type

mysql> select *from indexOnIntColumnDemo where UserId=1004;

The output is as follows

+--------+----------+---------+
| UserId | UserName | UserAge |
+--------+----------+---------+
| 1004  | Mike      | 26      |
+--------+----------+---------+
1 row in set (0.00 sec)
raja
Published on 01-Apr-2019 15:17:36
Advertisements