»  Home  »  Programming  »  Introduction to Database Indexes
Introduction to Database Indexes
By Chris Smith | Published 02/15/2006 | Programming | Rating: ratingfullratingfullratingfullratingfullratingfull Unrated |
When Not To Index

Now that we've seen when we should use indexes, let's look at when we shouldn't use them. They can actually slow down your database (some databases may actually choose to ignore the index if there's no reason to use it).

A table like this:

CREATE TABLE news (
  newsid INT PRIMARY KEY,
  newstitle VARCHAR(255),
  newscontent TEXT,
  active CHAR(1),
  featured CHAR(1),
  newsdate TIMESTAMP
);

... looks pretty standard. The 'active' field tells us whether the news item is active and ready to be viewed on the site.

So... should we should create an index on this field for a query like this?

SELECT newsid, newstitle FROM news WHERE active='1';

No, we shouldn't.

If most of your content is live, this index will take up extra space and slow the query down because almost all of the fields match this criteria. Imagine 500 news items in the database with 495 being active. It's quicker to eliminate the ones that aren't active than it is to list all of the active ones (if you do have an index on the 'active' field, some databases will choose to ignore it anyway because it will slow the query down).

The featured field tells us whether the news item should feature on the front page. Should we index this field? Yes. Most of our content is not featured, so an index on the 'featured' column will be quite useful.

Other examples of when to index a field include if you're going to order by it in a query. To get the most recent news items, we do a query like this:

SELECT newtitle, newscontent FROM news ORDER BY newsdate DESC;

Creating an index on 'newsdate' will allow the database to quickly sort the results so it can fetch the items in the right order. Indexing can be a bit tricky to get right, however there are tools available for each database to help you work out if it's working as it should.
Pages: « Back  1 2 3 4 5  Next » 

Article Series

This article is part 3 of a 4 part series. Other articles in this series are shown below:
  1. An Introduction to Databases
  2. An Introduction to Database Variable Types
  3. Introduction to Database Indexes
  4. Database Joins
Web designers: Learn how to attract more clients and profit like the big guys. Subscribe to our newsletter.