How to optimize a MySQL table after deleting some rows?


Use the OPTIMIZE TABLE command to optimize a MySQL table −

optimize table yourTableName;

Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Name) values('Bob');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.38 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------+
| Id | Name   |
+----+--------+
|  1 | Chris  |
|  2 | Robert |
|  3 | Bob    |
|  4 | David  |
+----+--------+
4 rows in set (0.00 sec)

Now let us delete rows from the table −

mysql> delete from DemoTable where Id IN(1,3);
Query OK, 2 rows affected (0.29 sec)
mysql> select *from DemoTable;
+----+--------+
| Id | Name   |
+----+--------+
|  2 | Robert |
|  4 | David  |
+----+--------+
2 rows in set (0.00 sec)

Following is the query to optimize the table created above and after deleting some rows −

mysql> optimize table DemoTable;

This will produce the following output −

+------------------+----------+----------+-------------------------------------------------------------------+
| Table            | Op       | Msg_type | Msg_text                                                          |
+------------------+----------+----------+-------------------------------------------------------------------+
| web.DemoTable    | optimize | note     | Table does not support optimize, doing recreate + analyze instead |
| web.DemoTable    | optimize | status   | OK                                                                |
+------------------+----------+----------+-------------------------------------------------------------------+
2 rows in set (4.32 sec)

Updated on: 03-Sep-2019

665 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements