SQL CREATE INDEX


David Haertzen David Haertzen, Tutorial Author
Check out our
Data Warehousing Tutorial.
Previous | Next

SQL > SQL Administration > SQL CREATE INDEX Statement

What is the SQL CREATE INDEX Statement?

The SQL INDEX TABLE statement is the SQL command that adds a new index to an existing table to an SQL database. Indexed enable faster and more efficient retrieval of information from SQL databases.

Why Use the SQL CREATE INDEX Statement?

SQL indexes are used because they can provide the following benefits / functions:

  • Rapid access of information
  • Efficient access of information
  • Enforcement of uniqueness constraints

Correct use of indexes can make the difference between a top performing database with high customer satisfaction and a non-performing database with low customer satisfaction.

How To Use the SQL CREATE INDEX Statement

The SQL CREATE INDEX command is used as follows.

SQL CREATE INDEX Statement Syntax

 
CREATE INDEX <index_type> <index_name> ON <table_name> (
<column_name1> <index_order>,
<column_name2> <index_order>,
)  
 
 
CREATE UNIQUE INDEX <index_type> <index_name> ON <table_name> (
<column_name1> <index_order>,
<column_name2> <index_order>,
)  

The number of characters that can make up SQL names for tables, columns and indexes varies by DBMS. In many cases the limit is 30 characters. The leading character of the name must be alphabetic - not a number or special character. The name of a new index can not duplicate the name of an existing index for the same table and should not be the same as a SQL reserved word. The underscore character can be used to improve readability. List elements are seperated by commas.

SQL CREATE INDEX Statement Example 1 - Rapid Access

The following example creates an non-unique index named IDX_PERSON_NAME on table PERSON with columns named person_name and gender_code in ascending sequence..

Here are the contents of the table:

Column NameDatatype Nullability
person_id INT NOT NULL
person_name VARCHAR(20) NOT NULL
social_security_nbrCHAR(9) NULL
gender_code CHAR(1) NULL
line_1_addr VARCHAR(50) NULL
city_name VARCHAR(50) NOT NULL
state_code CHAR(2) NOT NULL
zip_code CHAR(9) NOT NULL

This SQL CREATE VIEW Statement is executed:

 
CREATE INDEX IDX_PERSON_NAME ON PERSON
(person_name ASC, gender_code ASC)

 

SQL CREATE INDEX Statement Example 2 - Enforce Uniqueness

The following example creates a unique index named IDX_PERSON_SSN on table PERSON with the column named social_security_nnbr. This assures that two rows can not be added to the PERSON table with the same social security number.

This SQL CREATE TABLE Statement is executed:

 
CREATE UNIQUE INDEX IDX_PERSON_SSN ON PERSON
(social_security_nbr ASC)

 

Copyright© 1999-2015, First Place Software, Inc.