EN
MySQL - add index to existing table using ALTER TABLE
3
points
In this article, we would like to show you how to add index to an existing table in MySQL.
Quick solution:
ALTER TABLE `table_name`
ADD INDEX `index_name` (`column2`, `column2`, `columnN`);
Practical example
To show how to add index to existing table using ALTER TABLE
, we will use the following table:
Note:
At the end of this article you can find database preparation SQL queries.
Example 1 - one column index
In this example, we will create an index for the salary
column in users
table.
Query:
ALTER TABLE `users`
ADD INDEX `index_salary` (`salary`);
Result:
1. Using query
SHOW INDEX FROM `users` FROM `dirask`; -- where users-table_name, dirask-database_name
2. Using HeidiSQL
Example 2 - multiple column index
In this example, we will create an index on two columns using ALTER TABLE
statement.
Query:
ALTER TABLE `users`
ADD INDEX `index_full_name` (`name`, `surname`);
Result:
1. Using query
SHOW INDEX FROM `users` FROM `dirask`; -- where users-table_name, dirask-database_name
2. Using HeidiSQL
Database preparation
create_tables.sql
file:
CREATE TABLE `users` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`surname` VARCHAR(50) NOT NULL,
`salary` DECIMAL(15,2) NOT NULL,
PRIMARY KEY (`id`)
);
insert_data.sql
file:
INSERT INTO `users`
( `name`, `surname`, `salary`)
VALUES
('John', 'Stewart', '3512.00'),
('Chris', 'Brown', '1344.00'),
('Kate', 'Lewis', '6574.00'),
('Ailisa', 'Gomez', '6500.00'),
('Gwendolyn', 'James', '4200.00'),
('Simon', 'Collins', '3320.00'),
('Taylor', 'Martin', '1500.00'),
('Andrew', 'Thompson', '2100.00');