Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are indexes from composite keys enough?

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?

like image 898
Alex Avatar asked Dec 20 '22 02:12

Alex


2 Answers

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.

like image 197
Michael Goldshteyn Avatar answered Jan 07 '23 07:01

Michael Goldshteyn


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.

like image 43
Mike Christensen Avatar answered Jan 07 '23 07:01

Mike Christensen