So I have a large table that I query (select only) quite frequently. The table is around 12,000 rows long. Since the advent of iOS, the time that it is taking to run these select queries has gone up 4-5x.
I was told that I need to add an index to my table. The query that I am using looks like this:
SELECT * FROM book_content WHERE book_id = ? AND chapter = ? ORDER BY verse ASC
How can I create an index for this table? Is it a command I just run once? What exactly is the index going to do? I didn’t learn about these in school so they still seem like some sort of magic to me at this point, so I was hoping to get a little instruction.
Thanks!
You want an index on book_id and chapter. Without an index, a server would do a
table scanand essentially load the entire table into memory to do its search. Do a quick search on theCREATE INDEXcommand for the RDBMS that you are using. You create the index once and every time you do anINSERTorDELETEorUPDATE, the server will update the index automatically. An index can beUNIQUEand it can be on multiple fields (in your case, book_id and chapter). If you make itUNIQUE, the database will not allow you to insert a second row with the same key (in this case, book_id and chapter). On most servers, having one index on two fields is different from having two individual indexes on single fields each.A Mysql example would be:
If you want only one record for each book_id, chapter combination, use this command:
A
PRIMARY INDEXis a special index that isUNIQUEandNOT NULL. Each table can only have one primary index. In fact, each table should have one primary index to ensure table integrity, especially during joins.