Question

This is how my table looks:

CREATE TABLE pics(
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT,
  page INTEGER,
  w INTEGER,
  h INTEGER,
  FOREIGN KEY(page) REFERENCES pages(id) ON DELETE CASCADE,
  UNIQUE(name, page)
);

CREATE INDEX "myidx" ON "pics"("page");  # is this needed?

so UNIQUE(name, page) should create an index. But is this index enough to make fast queries that involve the page field only? Like selecting a set of "pics" WHERE page = ?. or JOIN pages.id ON pics.page ? Or should I create another index (myidx) just for the page field?

Was it helpful?

Solution 2

Think of a composite index as a phone book. The phone book is sorted by last name, then the first name. If you're given the name Bob Smith, you can quickly find the S section, then Sm, then all the Smith's, then eventually Bob. This is fast because you have both keys in the index. Since the book is organized by last name first, it would also be just as trivial to find all the Smith entries.

Now imagine trying to find all the people named Bob in the entire phone book. Much harder, right?

This is analogous to how the index on disk is organized as well. Finding all the rows with a certain page column when the list of sorted in (name, page) order will basically result in a sequential scan of all the rows, looking one by one for anything that has that page.

For more information on how indexes work, I recommend reading through Use the Index, Luke.

OTHER TIPS

As stated, you will need your other myidx index, because your UNIQUE index specifies name first. In other words, it can be used to query by:

  1. name
  2. name and page
  3. But not by page alone.

Your other option is to reorder the UNIQUE index and place the page column first. Then it can be used for page only queries, but will become incompatible with name only queries.

You have to analyse the query(s) that will use this table and determine what fields the query will use to sort the results. You should index the fields that are used for sorting the most.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top