Mysql Indexes
Mysql Indexes
A database index is a data structure that improves the speed of operations in a table. Indexes can
be created using one or more columns, providing the basis for both rapid random lookups and
efficient ordering of access to records.
While creating index, it should be considered that what are the columns which will be used to
make SQL queries and create one or more indexes on those columns.
Practically, indexes are also type of tables, which keep primary key or index field and a pointer to
each record into the actual table.
The users cannot see the indexes, they are just used to speed up queries and will be used by
Database Search Engine to locate records very fast.
INSERT and UPDATE statements take more time on tables having indexes where as SELECT
statements become fast on those tables. The reason is that while doing insert or update, database
need to insert or update index values as well.
You can use one or more columns to create an index. For example, we can create an index on
tutorials_tbl using tutorial_author.
You can create a simple index on a table. Just omit UNIQUE keyword from the query to create
simple index. Simple index allows duplicate values in a table.
If you want to index the values in a column in descending order, you can add the reserved word
DESC after the column name.
ALTER TABLE tbl_name ADD PRIMARY KEY columnlist: This statement adds a PRIMARY
KEY, which means that indexed values must be unique and cannot be NULL.
ALTER TABLE tbl_name ADD UNIQUE index_name columnlist: This statement creates an
index for which values must be unique withtheexceptionofNULLvalues, whichmayappearmultipletimes.
ALTER TABLE tbl_name ADD INDEX index_name columnlist: This adds an ordinary index
in which any value may appear more than once.
ALTER TABLE tbl_name ADD FULLTEXT index_name columnlist: This creates a special
FULLTEXT index that is used for text-searching purposes.
You can drop any INDEX by using DROP clause along with ALTER command. Try out the following
example to drop above-created index.
You can drop any INDEX by using DROP clause along with ALTER command. Try out the following
example to drop above-created index.
Here is the example to add primary key in an existing table. This will make a column NOT NULL
first and then add it as a primary key.
To drop an index that is not a PRIMARY KEY, you must specify the index name.