
- MySQL - Home
- MySQL - Introduction
- MySQL - Features
- MySQL - Versions
- MySQL - Variables
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Node.js Syntax
- MySQL - Java Syntax
- MySQL - Python Syntax
- MySQL - Connection
- MySQL - Workbench
- MySQL Databases
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Show Database
- MySQL - Copy Database
- MySQL - Database Export
- MySQL - Database Import
- MySQL - Database Info
- MySQL Users
- MySQL - Create Users
- MySQL - Drop Users
- MySQL - Show Users
- MySQL - Change Password
- MySQL - Grant Privileges
- MySQL - Show Privileges
- MySQL - Revoke Privileges
- MySQL - Lock User Account
- MySQL - Unlock User Account
- MySQL Tables
- MySQL - Create Tables
- MySQL - Show Tables
- MySQL - Alter Tables
- MySQL - Rename Tables
- MySQL - Clone Tables
- MySQL - Truncate Tables
- MySQL - Temporary Tables
- MySQL - Repair Tables
- MySQL - Describe Tables
- MySQL - Add/Delete Columns
- MySQL - Show Columns
- MySQL - Rename Columns
- MySQL - Table Locking
- MySQL - Drop Tables
- MySQL - Derived Tables
- MySQL Queries
- MySQL - Queries
- MySQL - Constraints
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Replace Query
- MySQL - Insert Ignore
- MySQL - Insert on Duplicate Key Update
- MySQL - Insert Into Select
- MySQL Indexes
- MySQL - Indexes
- MySQL - Create Index
- MySQL - Drop Index
- MySQL - Show Indexes
- MySQL - Unique Index
- MySQL - Clustered Index
- MySQL - Non-Clustered Index
- MySQL Operators and Clauses
- MySQL - Where Clause
- MySQL - Limit Clause
- MySQL - Distinct Clause
- MySQL - Order By Clause
- MySQL - Group By Clause
- MySQL - Having Clause
- MySQL - AND Operator
- MySQL - OR Operator
- MySQL - Like Operator
- MySQL - IN Operator
- MySQL - ANY Operator
- MySQL - EXISTS Operator
- MySQL - NOT Operator
- MySQL - NOT EQUAL Operator
- MySQL - IS NULL Operator
- MySQL - IS NOT NULL Operator
- MySQL - Between Operator
- MySQL - UNION Operator
- MySQL - UNION vs UNION ALL
- MySQL - MINUS Operator
- MySQL - INTERSECT Operator
- MySQL - INTERVAL Operator
- MySQL Joins
- MySQL - Using Joins
- MySQL - Inner Join
- MySQL - Left Join
- MySQL - Right Join
- MySQL - Cross Join
- MySQL - Full Join
- MySQL - Self Join
- MySQL - Delete Join
- MySQL - Update Join
- MySQL - Union vs Join
- MySQL Keys
- MySQL - Unique Key
- MySQL - Primary Key
- MySQL - Foreign Key
- MySQL - Composite Key
- MySQL - Alternate Key
- MySQL Triggers
- MySQL - Triggers
- MySQL - Create Trigger
- MySQL - Show Trigger
- MySQL - Drop Trigger
- MySQL - Before Insert Trigger
- MySQL - After Insert Trigger
- MySQL - Before Update Trigger
- MySQL - After Update Trigger
- MySQL - Before Delete Trigger
- MySQL - After Delete Trigger
- MySQL Data Types
- MySQL - Data Types
- MySQL - VARCHAR
- MySQL - BOOLEAN
- MySQL - ENUM
- MySQL - DECIMAL
- MySQL - INT
- MySQL - FLOAT
- MySQL - BIT
- MySQL - TINYINT
- MySQL - BLOB
- MySQL - SET
- MySQL Regular Expressions
- MySQL - Regular Expressions
- MySQL - RLIKE Operator
- MySQL - NOT LIKE Operator
- MySQL - NOT REGEXP Operator
- MySQL - regexp_instr() Function
- MySQL - regexp_like() Function
- MySQL - regexp_replace() Function
- MySQL - regexp_substr() Function
- MySQL Fulltext Search
- MySQL - Fulltext Search
- MySQL - Natural Language Fulltext Search
- MySQL - Boolean Fulltext Search
- MySQL - Query Expansion Fulltext Search
- MySQL - ngram Fulltext Parser
- MySQL Functions & Operators
- MySQL - Date and Time Functions
- MySQL - Arithmetic Operators
- MySQL - Numeric Functions
- MySQL - String Functions
- MySQL - Aggregate Functions
- MySQL Misc Concepts
- MySQL - NULL Values
- MySQL - Transactions
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - SubQuery
- MySQL - Comments
- MySQL - Check Constraints
- MySQL - Storage Engines
- MySQL - Export Table into CSV File
- MySQL - Import CSV File into Database
- MySQL - UUID
- MySQL - Common Table Expressions
- MySQL - On Delete Cascade
- MySQL - Upsert
- MySQL - Horizontal Partitioning
- MySQL - Vertical Partitioning
- MySQL - Cursor
- MySQL - Stored Functions
- MySQL - Signal
- MySQL - Resignal
- MySQL - Character Set
- MySQL - Collation
- MySQL - Wildcards
- MySQL - Alias
- MySQL - ROLLUP
- MySQL - Today Date
- MySQL - Literals
- MySQL - Stored Procedure
- MySQL - Explain
- MySQL - JSON
- MySQL - Standard Deviation
- MySQL - Find Duplicate Records
- MySQL - Delete Duplicate Records
- MySQL - Select Random Records
- MySQL - Show Processlist
- MySQL - Change Column Type
- MySQL - Reset Auto-Increment
- MySQL - Coalesce() Function
MySQL - Create Index
A database index improves the speed of operations in a database table. They can be created on one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records.
Practically, indexes are a special type of lookup tables, that hold a pointer to each record into the actual table.
We can create indexes on a MySQL table in two scenarios: while creating a new table and on an existing table.
Creating Indexes on New Table
If we want to define an index on a new table, we use the CREATE TABLE statement.
Syntax
Following is the syntax to create an index on a new table −
CREATE TABLE( column1 datatype PRIMARY KEY, column2 datatype, column3 datatype, ... INDEX(column_name) );
Example
In this example, we are create a new table CUSTOMERS and adding an index to one of its columns using the following CREATE TABLE query −
CREATE TABLE CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25), SALARY DECIMAL (18, 2), INDEX(ID) );
To verify whether the index has been defined or not, we check the table definition using the following DESC statement.
DESC CUSTOMERS;
Output
The table structure displayed will contain a MUL index on the ID column as shown −
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
ID | int | NO | MUL | NULL | |
NAME | varchar(20) | NO | NULL | ||
AGE | int | NO | NULL | ||
ADDRESS | char(25) | YES | NULL | ||
SALARY | decimal(18, 2) | YES | NULL |
Creating Indexes on Existing Table
To create an index on existing table, we use the following SQL statements −
- With CREATE INDEX Statement
- With ALTER Command
CREATE INDEX Statement
The basic syntax of the CREATE INDEX statement is as follows −
CREATE INDEX index_name ON table_name;
In the following example, let us create an index on CUSTOMERS table. We are using CREATE INDEX statement here −
CREATE INDEX NAME_INDEX ON CUSTOMERS (Name);
To check if the index is created on the table or not, let us display the table structure using DESC statement as shown below −
DESC CUSTOMERS;
Output
As we can see in the table below, a composite index is created on the 'NAME' column of CUSTOMERS table.
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
ID | int | NO | MUL | NULL | |
NAME | varchar(20) | NO | MUL | NULL | |
AGE | int | NO | NULL | ||
ADDRESS | char(25) | YES | NULL | ||
SALARY | decimal(18, 2) | YES | NULL |
ALTER... ADD Command
Following is the basic syntax of ALTER statement −
ALTER TABLE tbl_name ADD INDEX index_name (column_list);
Let us use ALTER TABLE... ADD INDEX statement in the following example to add an index to the CUSTOMERS table −
ALTER TABLE CUSTOMERS ADD INDEX AGE_INDEX (AGE);
Output
As we can see in the table below, another composite index is created on the 'AGE' column of CUSTOMERS table.
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
ID | int | NO | MUL | NULL | |
NAME | varchar(20) | NO | MUL | NULL | |
AGE | int | NO | MUL | NULL | |
ADDRESS | char(25) | YES | NULL | ||
SALARY | decimal(18, 2) | YES | NULL |
Simple and Unique Index
A unique index is the one which cannot be created on two rows at once. Following is the syntax to create a unique index −
CREATE UNIQUE INDEX index_name ON table_name ( column1, column2,...);
Example
Following example creates a unique index on the table temp −
CREATE UNIQUE INDEX UNIQUE_INDEX ON CUSTOMERS (Name);
Composite Indexes
We can also create an index on more than one column and it is called a composite index the basic syntax to create a composite index is as follows −
CREATE INDEX index_name on table_name (column1, column2);
Example
Following query creates a composite index on the ID and Name columns of the above created table −
CREATE INDEX composite_index on CUSTOMERS (ID, Name);
Creating an Index Using Client Program
In addition to using SQL queries, we can also create an index on a table in a MySQL database using a client program.
Syntax
Following are the syntaxes to create an index in a MySQL database using various programming languages −
The MySQL PHP connector mysqli provides a function named query() to execute the CREATE INDEX query in the MySQL database.
$sql=" CREATE INDEX index_name ON table_name (column_name)"; $mysqli->query($sql);
The MySQL NodeJS connector mysql2 provides a function named query() to execute the CREATE INDEX query in the MySQL database.
sql = "CREATE INDEX index_name ON table_name (column1, column2, ...)"; con.query(sql);
We can use the JDBC type 4 driver to communicate to MySQL using Java. It provides a function named executeUpdate() to execute the CREATE INDEX query in the MySQL database.
String sql = " CREATE INDEX index_name ON table_name (column_name)"; statement.executeUpdate(sql);
The MySQL Connector/Python provides a function named execute() to execute the CREATE INDEX query in the MySQL database.
create_index_query = CREATE INDEX index_name ON table_name (column_name [ASC|DESC], ...); cursorObj.execute(create_index_query);
Example
Following are the implementations of this operation in various programming languages −
$dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'password'; $dbname = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ($mysqli->connect_errno) { printf("Connect failed: %s", $mysqli->connect_error); exit(); } // printf('Connected successfully.'); // CREATE INDEX $sql = "CREATE INDEX tid ON tutorials_table (tutorial_id)"; if ($mysqli->query($sql)) { printf("Index created successfully!."); } if ($mysqli->errno) { printf("Index could not be created!.", $mysqli->error); } $mysqli->close();
Output
The output obtained is as follows −
Index created successfully!.
var mysql = require('mysql2'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "Nr5a0204@123" }); //Connecting to MySQL con.connect(function (err) { if (err) throw err; console.log("Connected!"); console.log("--------------------------"); sql = "create database TUTORIALS" con.query(sql); sql = "USE TUTORIALS" con.query(sql); sql = "CREATE TABLE temp(Name VARCHAR(255), age INT, Location VARCHAR(255));" con.query(sql); sql = "INSERT INTO temp values('Radha', 29, 'Vishakhapatnam'), ('Dev', 30, 'Hyderabad');" con.query(sql); //Creating an Index sql = "CREATE INDEX sample_index ON temp (name);" con.query(sql); //Describing the table sql = "DESC temp;" con.query(sql, function(err, result){ if (err) throw err console.log(result); }); });
Output
The output produced is as follows −
Connected! -------------------------- [ {Field: 'Name',Type: 'varchar(255)',Null: 'YES',Key: 'MUL',Default: null,Extra: ''}, {Field: 'age',Type: 'int',Null: 'YES',Key: '',Default: null,Extra: ''}, {Field: 'Location',Type: 'varchar(255)',Null: 'YES',Key: '',Default: null,Extra: ''} ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class CreateIndex { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String username = "root"; String password = "password"; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); System.out.println("Connected successfully...!"); //Create an index on the tutorials_tbl...!; String sql = "CREATE INDEX tid ON tutorials_tbl (tutorial_id)"; statement.executeUpdate(sql); System.out.println("Index created Successfully...!"); connection.close(); } catch (Exception e) { System.out.println(e); } } }
Output
The output obtained is as shown below −
Connected successfully...! Index created Successfully...!
import mysql.connector #establishing the connection connection = mysql.connector.connect( host='localhost', user='root', password='password', database='tut' ) cursorObj = connection.cursor() create_index_query = "CREATE INDEX idx_submission_date ON tutorials_tbl (submission_date)" cursorObj.execute(create_index_query) connection.commit() print("Index created successfully.") cursorObj.close() connection.close()
Output
Following is the output of the above code −
Index created successfully.