Introducing Database Indexes0:00
An index can be a fairly confusing thing to understand, at least initially. So let's use a real-life example. Here I have a video_downloads table, and if we take a look at the content, for each record I store the user_id and the video_id that they downloaded. So it's a simple way to track all downloaded content on the website. Now if I return to the structure, you'll see other than the primary key, we don't have a single index applied. And it's even possible right now you don't even know what an index is. So let's use some real-world examples to figure this out. So let's say I'm going to select * from video_downloads table, but maybe limit
Baseline Query Performance0:32
So let's use some real-world examples to figure this out. So let's say I'm going to select * from the video_downloads table, but maybe limit it to one user. So I want all the videos that have been downloaded by a single user, anyone. Okay, so if I give that a run, we get, it looks like, 21 records here. But if we take a look at the bottom, it took 300 milliseconds. Let's run it a few more times. Yep, about a third of a second. Now by any human metric, that's less than a second. It's incredibly fast.
Using EXPLAIN to Analyze2:42
This is basically a real-world parallel for an index. It's an index by the last name of the person. So let's try this. It sounds like we need an easier way to hunt down the user ID. And in fact, let me show you something real quick. Let's explain this query. So I'm going to give that a run and you'll see information about the query. I want you to take a look at two things here, the type and the rows. So the type, this gets a little confusing and I'm not sure how much we want to go into it.
Adding an Index3:38
And it's no coincidence that because they match up, we also have a type of all. This means the database has to hunt through every single record. There's no filtering. There's no sorting in place. It's almost like that white pages example before it was sorted in alphabetical order. And that's why it's so slow. Let's add an index. We'll do it right here. Index on the User ID. Okay.
Comparing Performance After Index4:00
Index on the user ID. Okay. So notice it takes a couple seconds because it's sort of like creating its own separate database. Not quite, but it's almost like it's creating another stack and balancing it so that you can then very rapidly track down what you're looking for. Okay. So now I'm going to bring back this query, run it, and notice this time the query took less than one millisecond. So before it was 300 milliseconds.
