Database Indexes Explained: Why Your Queries Are Slow and How to Fix Them
The Qtec Mastery
Author
A query that runs instantly on your laptop can crawl once the table holds a few years of real records. Very often the cause is a missing index. This guide to database indexing is for beginners and junior developers using MySQL: you will learn what an index is, how to create one, how to check that MySQL is actually using it with EXPLAIN, and when an index does more harm than good.
A database index is a sorted lookup structure that lets the database find matching rows without reading the whole table, like the index at the back of a book. You create one with |
Databases from Zero, part 5 of 6. Previous: Database Design for Beginners: Tables, Keys and Normalisation · Next: MySQL vs PostgreSQL vs MongoDB: Which Database Should You Learn First?
What is a database index?
Picture a 600-page textbook with no index at the back. To find every page that mentions "M-Pesa", you would have to read the whole book. With an index, you look up "M-Pesa", see "pages 42, 187, 390" and go straight there.
A database index works the same way. It keeps a sorted copy of one or more columns, each value pointing to the rows that contain it. In MySQL's default storage engine, InnoDB, most indexes are B-tree structures, which stay sorted as data changes and can be searched very quickly.
Without an index, MySQL has to do a full table scan: read every row and check it. On a five-row table nobody notices. On large tables an index can be the difference between scanning every row and jumping straight to the match.
Which indexes do I already have?
Some indexes exist without you asking. We use the college database from part 2 of this series:
- Every
PRIMARY KEYis an index. In InnoDB, the table's rows are actually stored in primary key order. - Every
UNIQUEcolumn gets an index, sostudents.phoneandpayments.mpesa_codeare already indexed. - Every foreign key column needs an index, and InnoDB creates one automatically if none exists. So
payments.student_idis indexed too.
Check for yourself:
SHOW INDEX FROM payments;
You will see PRIMARY, mpesa_code and an index on student_id that MySQL created for the foreign key.
How do I create an index in MySQL?
The bursar often searches students by county. Nothing indexes county yet, so let's add an index:
CREATE INDEX idx_students_county ON students (county);
The name is up to you. A pattern like idx_table_column makes indexes easy to recognise later. To remove one:
DROP INDEX idx_students_county ON students;
(Keep it for now, we use it below.) You can also declare indexes when you create a table, with a line like INDEX idx_students_county (county) inside CREATE TABLE.
How do I check if a query uses an index with EXPLAIN?
Put EXPLAIN in front of a SELECT and MySQL tells you its plan instead of running the query:
EXPLAIN SELECT full_name FROM students WHERE county = 'Kisumu';
The output has several columns. These are the ones to read first. Before the index existed, you would see something like:
| type | possible_keys | key | rows | Extra |
|---|---|---|---|---|
| ALL | NULL | NULL | 5 | Using where |
And after creating idx_students_county:
| type | possible_keys | key | rows | Extra |
|---|---|---|---|---|
| ref | idx_students_county | idx_students_county | 1 | NULL |
- type:
ALLmeans a full table scan, the one to worry about on big tables.ref,eq_ref,rangeandconstmean an index is being used. - key: the index MySQL actually chose.
NULLmeans none. - rows: MySQL's estimate of how many rows it must examine. Lower is better.
The exact numbers come from table statistics and can vary, and on a tiny table MySQL sometimes decides a full scan is cheaper anyway. Test with realistic amounts of data. From MySQL 8.0.18 you can also run EXPLAIN ANALYZE, which really executes the query and reports actual timings and row counts.
What is a composite index, and does column order matter?
A composite index covers several columns. A very common query is "show this student's payments in date order":
SELECT mpesa_code, amount_kes, paid_on
FROM payments
WHERE student_id = 2
ORDER BY paid_on;
An index on both columns, in this order, serves the filter and the sort together:
CREATE INDEX idx_payments_student_paid ON payments (student_id, paid_on);
Column order matters a lot. Think of a phone book sorted by surname, then first name. It is great for finding "Otieno" or "Otieno, Brian", but useless for finding everyone called "Brian". That is the leftmost prefix rule: MySQL can use the index for the first column, or the first and second, but not normally for the second column alone.
| Query filter | Uses (student_id, paid_on)? |
|---|---|
WHERE student_id = 2 | Yes |
WHERE student_id = 2 AND paid_on >= '2026-02-01' | Yes, both columns |
WHERE student_id = 2 ORDER BY paid_on | Yes, and no extra sort needed |
WHERE paid_on >= '2026-02-01' | Not normally |
(MySQL 8 has a "skip scan" optimisation that can occasionally use the second column alone, but do not design around it.) A good rule of thumb: put columns tested with = first and the column used for a range or sort last.
A bonus: this new index starts with student_id, so it can also serve the foreign key. MySQL may then drop the index it created automatically for that foreign key, because it is no longer needed.
Should I index foreign keys?
Yes. Foreign key columns are what you join on, and joins without an index on the joined column get slow quickly. As we saw, InnoDB indexes foreign keys automatically when you declare the constraint. The trap is a column that acts like a foreign key without being declared as one. In the original schema, students.course_id has no constraint, so it has no index. If you added the constraint in part 4, MySQL indexed it for you. If not, add one yourself:
CREATE INDEX idx_students_course ON students (course_id);
Now the joins from part 3, such as students s INNER JOIN courses c ON s.course_id = c.course_id, have an index to use on both sides.
When do indexes hurt?
- Every write gets slower. Each
INSERT,UPDATEorDELETEmust update every index on the table as well as the row. A payments table that receives constant M-Pesa callbacks should not carry ten indexes "just in case". - They use disk space and memory. Indexes are stored alongside the table, and MySQL works best when the busy ones fit in memory.
- Low-selectivity columns gain little. An index on a column with only a few distinct values, such as a yes/no
is_activeflag where nearly every row says yes, rarely helps. MySQL often ignores it and scans the table. - Duplicates waste effort. An index on
(county)is redundant once you have one on(county, enrolled_on), because the composite covers it.
Also watch for queries that stop an index being used even when it exists:
- Wrapping the column in a function:
WHERE YEAR(paid_on) = 2026cannot use a normal index onpaid_on. Write a range instead:WHERE paid_on >= '2026-01-01' AND paid_on < '2027-01-01'. - A leading wildcard:
LIKE 'Brian%'can use an index,LIKE '%Otieno'cannot.
Practice exercise
- The admissions team often runs
SELECT full_name FROM students WHERE county = 'Nairobi' AND enrolled_on >= '2026-01-01';. Create the best index for it, and tidy up any index it makes redundant. - Rewrite
SELECT * FROM students WHERE YEAR(enrolled_on) = 2026;so that an index onenrolled_oncould be used. - How would you confirm that your index from task 1 is being used?
Answers
-- 1: equality column first, range column last
CREATE INDEX idx_students_county_enrolled ON students (county, enrolled_on);
-- If you still have the single-column index from earlier, it is now redundant:
-- DROP INDEX idx_students_county ON students;
-- 2
SELECT * FROM students
WHERE enrolled_on >= '2026-01-01' AND enrolled_on < '2027-01-01';
-- 3
EXPLAIN SELECT full_name FROM students
WHERE county = 'Nairobi' AND enrolled_on >= '2026-01-01';
-- look for key = idx_students_county_enrolled and type = range
Go beyond the basicsDBMS 2 covers performance, indexing, query plans and day-to-day database administration over 10 weeks online, with a certificate on completion. Also useful: DBMS 1: Database Foundations and SQL (10 weeks, KES 20,000) |
Frequently asked questions
Does an index make every query faster?No. It speeds up reads that filter, join or sort on the indexed columns, and slows down writes slightly. Index for the queries you actually run. Should I index every column?No. Start with primary keys, foreign keys and the columns in your most frequent Does a primary key create an index?Yes. In MySQL every primary key is an index, and so is every Do indexes work the same in PostgreSQL?The ideas are the same: B-tree indexes, composite indexes, the leftmost prefix rule and |
Comments (0)
Search Blog
Categories
Popular Posts
Why Traditional Education is Failing Future Developers: The QTEC Approach
326 views
What Is Frontend Development? A Beginner's Guide
121 views
What Is a Database? A Beginner's Guide With Real Kenyan Examples
35 views
Git and GitHub for Beginners: The Commands You Will Actually Use
33 views
Computer Packages Course in Kenya: Fees, Duration and Certificate (2026)
32 views
You Might Also Like
What Is a Database? A Beginner's Guide With Real Kenyan Examples
Every app you use, from your school portal to M-Pesa, keeps its information some...
Read More →
SQL for Beginners: 10 Queries You Will Use Every Day
Most of the SQL people write at work comes down to about ten patterns. This guid...
Read More →
SQL JOINs Explained Simply: INNER, LEFT and RIGHT JOIN With Examples
Real databases split information across several tables, so sooner or later you n...
Read More →