You don't always need JOINs
You don't *always* need joins, and sometimes it's faster to not use them 🤯
Everything I said
Suggesting that you don't need joins in MySQL may sound like blasphemy, but I promise I'm gonna back it up. There are several times when people reach for joins, when a join feels natural, but something else, in fact, may be better. For these examples, we're gonna have two tables. We're gonna have a users table, and we're gonna have a posts table. A user can have many posts, and a post has a title, body, and a view count.
We're gonna try to find users that have written popular posts, popular being defined as m- more than ninety thousand views. The way that we can do this using a join is pretty straightforward. We'll say SELECT Star FROM Users LEFT JOIN Posts ON Users ID = Posts User ID. Pretty straightforward join here. That's not exactly what we're looking for.
We need to say WHERE Views 90000, and that gets us close, but that doesn't fulfill the exact requirement. The exact requirement was find the users that have written popular posts, not find the users and their posts. So now we have just the users that have written popular posts. However, we did something a little bit wrong here.
We have duplicates here. So we have 131 rows coming back, but if we throw a DISTINCT on the front of this, we now have 126 rows coming back. So some user, some lucky user, has written a couple of posts that have gotten more than 90000 views. The problem is, we're joining in the posts table, which can cause a duplication in the users table, and then we're throwing away all the post data after we filter on it, and then we're de-duplicating the user data.
Doesn't seem like the best way, does it? I agree. So instead of doing any of that, we're just gonna start over. If we start the other direction, SELECT Star FROM Posts WHERE Views 90000, and I don't know what this gets us. But if we go User ID, this doesn't get us very far either because we have to throw a DISTINCT on here and then join the users back in.
So we're approaching the problem from the opposite direction with the same results. However, this is, this set right here is the correct set of user IDs. And what you may be tempted to do here is run two queries. One, to get all of the user IDs, pull them back over the wire into your application, bind that into a second query, which you then issue to get the users.
There is such a thing as query decomposition, and it can make it faster. In this case, I don't think it's a good idea. I don't think it's a good idea to pull hundreds, potentially thousands, of IDs over the wire just to turn around and issue them back. So instead, we're gonna do it the right way, and the right way is to use a subquery. So we're gonna say SELECT Star FROM Users WHERE ID is IN.
So we're filtering on the ID, and this is where you may be familiar with hard coding IDs or binding values in from your application. But instead, we're just gonna put this entire query. In fact, we don't even need the DISTINCT anymore. So if we run this, we'll see that we get back our 126 people with no posts data, with no duplication whatsoever.
And we're not done yet, but I wanna pause for one second to talk about some of the fear or some of the information that's out there regarding subqueries. You may see on Stack Overflow something along the lines of, "Never use a subquery. Everything should be a join." You may see that on Stack Overflow. You may get that feedback in a PR review.
That used to be more true. That, that used to maybe be totally true. But as of MySQL 8, and I think more specifically 8.0.17, it introduced this, um, semi-join and anti-join optimization. So now, when MySQL looks at a subquery like this, it says, "I know exactly what you're trying to do.
I'm going to kind of do a join. I'm gonna do a semi-join, or if you're negating it, I'm gonna do an anti-join." But all that being said, these subqueries are fine. They are incredibly performant. They are probably faster than using a join and deduplication to get this same result. Let's keep going. There's another way that we can write this, which may be more performant according to the documentation.
So if we copy this, we copy this and we come down here, we'll change this to an EXISTS statement. Instead of saying ID IN, we're just looking for the existence of something in the inner query, but we need to bind the outer query and the inner query back together. So we'll say AND Users.ID = User ID, and that links those two back together. So if we run this, we get our 126, and if we run that, we get our 126.
In this case, in this particular case, the EXPLAIN plan ends up being the same thing, but this is an optimization, and the reason that this is an optimization is MySQL is gonna work from the outside in. And so what we're doing is we are now limiting the scope of this inner query to only rows from the outer query.
And so this is an optimization to potentially work with less data and have more restrictive filtering on the subquery inside. I'm gonna show you just a quick and dirty benchmark here. I don't love benchmarks 'cause it's so dependent on the setup and the data and the configuration and everything, but I do wanna show you that in this constrained environment with this data, the subquery is faster.
I've told you why it's faster. I've told you that it's faster. I just kinda wanna show you that it's faster, but please test on your own data. I'm gonna show you just the setup here, and then we'll go ahead and run it. So I have this first SQL statement, which is the JOIN style DISTINCT Users Star LEFT JOIN the Posts IN where the Views is greater than 90000. Nothing new there.
And then both subquery styles, the WHERE ID IN and the WHERE EXISTS. All the same things we've been doing. The first thing I'm gonna do is I'm actually going to run all three of these. I'm gonna run all three of these and, uh, JSON encode the results and MD5 hash it, and that's just a nice way for me to tell if we're getting the same results.
So we have all of the same hashes. So we are getting the exact same result set. That's a nice sanity check. And then I'm gonna pull just one of them out. We know that they're hashing out to the exact same thing, but what if all three of them are null? That would be embarrassing. So that actually looks like we are getting the results back that we want. Those are our users. So we can clear that out and come back here and run the benchmark.
So the way that we're gonna do this is we're gonna run the JOIN, the subquery one, subquery two by actually running these queries, and we're gonna run each one 100 times. So if we hop back over here, we should see... There you go. So the JOIN is twice as slow as both subqueries. These subqueries are gonna be about the same. If we run it again, I bet we see, it looks like- Subquery two is a little bit faster.
There you go. Subquery one and two are the same, and the join is quite a bit slower. So in this case, that, that result is durable. You would need to test on your data. I think if we tested with even more data, it might actually be more pronounced, but this is just a nice, quick, and dirty way to prove what we've been talking about. So what is the pattern here? If I'm telling you you don't need joins, we both know that that's not always true.
Sometimes you need joins, but hopefully I've proven sometimes you don't need a join. I think the pattern is when you're pulling data from table A based on data from table B, but you don't want the data from table B to be brought along. You're filtering on a related table, but you don't need the information from the related table to be returned to you.
If you do need the information from the related table, you have to join it in. If you don't need it, don't join it in, create duplication in the table that you actually want that you then have to de-duplicate back down to the results that you're actually looking for. Instead, use a subquery, which under the hood is gonna be transformed into a semi-join or an anti-join.
It's gonna do the filtering on the table that you want. If you liked this video, we've got tons of MySQL videos on this channel. Please, please subscribe, make my boss, Holly, very happy. Until the next time, see ya.