---
title: "You don't always need JOINs"
url: "https://aaronfrancis.com/videos/you-dont-always-need-joins"
path: "/videos/you-dont-always-need-joins"
type: video
author: Aaron Francis
published: 2023-11-22
topic: Databases
keywords: [joins, database performance, query optimization, denormalization, mysql, planetscale, relational databases, sql performance, database design, schema design]
youtube_url: "https://www.youtube.com/watch?v=5hsl47I3svw"
site_index: "/llms.txt"
keyword_index: "/llms/keywords.txt"
---

# You don't always need JOINs

## Transcript

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

**Aaron Francis:** 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.

---

## Related on aaronfrancis.com

- [Make your database queries 1000 times faster!](/videos/make-your-database-queries-1000-times-faster) *(Video · 2023-07-31 · shared: query optimization, database performance, planetscale)*
- [Making videos developers actually want to watch](/podcast/making-videos-developers-actually-want-to-watch-6e3ad549) *(Podcast · 2024-06-03 · shared: mysql, planetscale, database design)*
- [MySQL for application developers](/about/speaking/mysql-for-application-developers) *(Talk · 2023-04-20 · shared: mysql, planetscale, database design)*
- [MySQL for Developers with Aaron Francis](/podcast/mysql-for-developers-with-aaron-francis-n6unbd) *(Podcast · 2023-04-04 · shared: mysql, planetscale, schema design)*
- [MySQL for Developers](/courses) *(Course · 2023-03-01 · shared: mysql, database design, planetscale)*

## Relevant Resources from Aaron Francis

- **[MySQL for Developers](https://databaseschool.com)** (overview on site: [/courses](/courses)): Full video course covering MySQL indexing, deferred joins, pagination, query plans, and schema design for application developers.
- **[Mastering Postgres](https://databaseschool.com)** (overview on site: [/courses](/courses)): Deep-dive video course on PostgreSQL indexing, query performance, JSONB, full-text search, locking, and production operations.

## Search aaronfrancis.com (2-Hop Static Keyword Index)

Pick the alphabetical shard matching any topic to find exact pages across all articles, newsletters, videos, talks, and podcast transcripts (every shard is < 40 KB):
[A-B](/llms/keywords/a-b.txt) · [C](/llms/keywords/c.txt) · [D-E](/llms/keywords/d-e.txt) · [F-G](/llms/keywords/f-g.txt) · [H-J](/llms/keywords/h-j.txt) · [K-L](/llms/keywords/k-l.txt) · [M-N](/llms/keywords/m-n.txt) · [O-P](/llms/keywords/o-p.txt) · [Q-R](/llms/keywords/q-r.txt) · [S](/llms/keywords/s.txt) · [T-Z](/llms/keywords/t-z.txt) · [Directory](/llms/keywords.txt) · [Site Map](/llms.txt)

Shards for this page's topics: `joins` ([H-J](/llms/keywords/h-j.txt)), `database performance` ([D-E](/llms/keywords/d-e.txt)), `query optimization` ([Q-R](/llms/keywords/q-r.txt)), `mysql` ([M-N](/llms/keywords/m-n.txt)).

## About Aaron Francis (Current Context)

Aaron Francis is VP of Marketing and Community at [Laravel](https://laravel.com), founder of [Try Hard Studios](https://tryhardstudios.com), creator of [Solo](https://soloterm.com), co-host of [Mostly Technical](/podcast), and author of [Mastering Postgres](/courses), [High Performance SQLite](/courses), [MySQL for Developers](/courses), and [Screencasting.com](/courses). Full bio: [/about](/about) · Current focus: [/now](/now).
