Indexes When to Use and When to Avoid In SQL. _ by BaseCS101 _ Level Up Coding
Indexes When to Use and When to Avoid In SQL. _ by BaseCS101 _ Level Up Coding
Search Write
Member-only story
BaseCS101 · Follow
Published in Level Up Coding · 4 min read · Jan 27, 2023
70
Indexing
Through this article, we’ll learn what indexes are, why to use them, how to
create them, and when to avoid them. The concept of indexes is mostly
asked in the interviews which are focused on SQL.
What Is an Index?
Indexes are a special kind of lookup table that is used by the database search
engine to speed up data retrieval from the tables. Basically, an index is a
pointer that points to the tuples of a table.
For such scenarios, indexes are very useful to query the tables and get the
results very quickly. If the records of the table would have been sorted then
it would have been easier to search the record.
sorted records on name
In the above example, records of the table are sorted on the basis of id’s, and
to search for a name in the table we have to iterate through all the records of
the table for finding a match. This would take a linear time that is O(n) .
Hence we can have an index on the name which is sorted alphabetically and
points to actual records of the table. Using this index searching for a name
would take log(n) time as the records are alphabetically sorted and a binary
search can be performed.
The below syntax creates an index (index_name) on a table. This index will
allow duplicate values.
Note: The syntax for creating indexes varies among different databases. So check
the syntax for creating indexes in your database.
MySQL:
ALTER TABLE table_name
DROP INDEX index_name;
MS Access:
SQL Server:
DB2/Oracle:
We should look at the column(s) that are used very frequently in the query’s WHERE
If the WHERE clause uses a single column for filtering the rows then a single-
column index is good otherwise if multiple columns are used for filtering
then a composite index is suitable.
Lists