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?
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:
name
name
and page
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With