CREATE INDEX - Statement to Create Indexes

A tutorial example is provided on how to create indexes as part of CREATE TABLE statements or using CREATE INDEX standalone statements.

There are two ways to create indexes on a table:

1. Creating indexes using the CREATE TABLE statement:

CREATE TABLE tbl_name (col_name col_type col_options, ...,
INDEX idx_name (idx_column, ...),...);

2. Creating indexes using the CREATE INDEX statement:

CREATE INDEX idx_name ON tbl_name (idx_column,...);

To show the indexes of an existing table, you can use the show index statement:

SHOW INDEX FROM tbl_name;

Here is an example code on creating indexes:

-- CreateIndex.sql
-- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
--
CREATE TABLE IF NOT EXISTS User (ID INT PRIMARY KEY AUTO_INCREMENT,
   Login CHAR(8) NOT NULL, Password CHAR(8) UNIQUE, 
   Email CHAR(32) DEFAULT 'info@hy.com',
   INDEX LoginIndex (Login));
INSERT INTO User VALUES (null,'herong','8IS3KOXW','herong@hy.comm');
INSERT INTO User (Login, Password, Email) 
   VALUES ('mike','PZ0JG',null);
INSERT INTO User (Login, Password) 
   VALUES ('mike','GZDN');
SELECT 'First show index';
SHOW INDEX FROM User;
CREATE INDEX EmailIndex ON User (Email);
SELECT 'Second show index';
SHOW INDEX FROM User;
DROP TABLE User;

Output:

First show index                                                        
First show index                                                        
Table	Non_unique Key_name	Seq_in_index	Column_name	
User	0          PRIMARY	1	        ID	
User	0          Password	1	        Password
User	1          LoginIndex	1	        Login	
Second show index                                                       
Second show index                                                       
Table	Non_unique Key_name	Seq_in_index	Column_name	
User	0	   PRIMARY	1	        ID	
User	0	   Password	1	        Password
User	1	   LoginIndex	1	        Login
User	1	   EmailIndex	1	        Email

Note that:

Last update: 2015.

Table of Contents

 About This Book

 Introduction of SQL

 MySQL Introduction and Installation

 Introduction of MySQL Programs

 Perl Programs and MySQL Servers

 PHP Programs and MySQL Servers

 Java Programs and MySQL Servers

 Datatypes and Data Literals

 Operations and Expressions

 Character Strings and Bit Strings

 Commonly Used Functions

 Table Column Types for Different Types of Values

Using DDL to Create Tables and Indexes

 CREATE TABLE - Statement to Create Tables

 Column Options When Creating Tables

CREATE INDEX - Statement to Create Indexes

 ALTER TABLE - Statement to Alter Table Structures

 Using DML to Insert, Update and Delete Records

 Using SELECT to Query Database

 Transaction Management and Isolation Levels

 Locks Used in MySQL

 Defining and Calling Stored Procedures

 Variables, Loops and Cursors Used in Stored Procedures

 Outdated Tutorials

 References

 PDF Printing Version