tags:

views:

84

answers:

6

What is index in SQL? Can you explain or reference to understand clearly?

Where should I use an index?

I searched in Stack Overflow, but it is still not clear to me.

A: 

An index is used for several different reasons. The main reason is to speed up querying so that you can get rows or sort rows faster. Another reason is to define a primary-key or unique index which will guarantee that no other columns have the same values.

Senseful
+1  A: 

An index is used to speed up searching in the database. MySQL have some good documentation on the subject (which is relevant for other SQL servers as well): http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

An index can be used to efficiently find all row matching some column in your query and then walk through only that subset of the table to find exact matches. If you don't have indexes on any column in the WHERE clause, the SQL server have to walk through the whole table and check every row to see if it matches, which may be a slow operation on big tables.

The index can also be a UNIQUE index, which means that you cannot have duplicate values in that column, or a PRIMARY KEY which in some storage engines defines where in the database file the value is stored.

In MySQL you can use EXPLAIN in front of your SELECT statement to see if your query will make use of any index. This is a good start for troubleshooting performance problems. Read more here: http://dev.mysql.com/doc/refman/5.0/en/explain.html

Emil Vikström
The question title states SQL Server. Yet accepted answer is MySQL ?
Mitch Wheat
A: 

If you're using SQL Server, one of the best resources is its own Books Online that comes with the install! It's the 1st place I would refer to for ANY SQL Server related topics.

If it's practical "how should I do this?" kind of questions, then StackOverflow would be a better place to ask.

Also, I haven't been back for a while but sqlservercentral.com used to be one of the top SQL Server related sites out there.

cloneofsnake
A: 

Well in general index is binary tree. There are two types of indexes: clustered and nonclustered. Clustered index creates a physical order of rows (it can be only one and in most cases it is also a primary key - if you create primary key on table you create clustered index on this table also). Noclustered index is also a binary tree but it doesn't create a physical order of rows. So the leave nodes of nonclustered index contan PK (if it exists) or row index. Indexes are used to increase speed of search. Because it that case it is O(log N). Indexes is very large and interesting topic. I can say that creating indexes on lagre database is some kind of art sometimes.

Voice
in general, its a b-tree rather than a binary tree.
Mitch Wheat