Subquery vs JOIN
This article is a complementary resource to the Learn SQL Basics course.
This article is a complementary resource to the Learn SQL Basics course.
Subquery vs JOIN
You often need to retrieve data from multiple tables when working with SQL. JOINs and subqueries are key techniques for this, but they serve different purposes.
The best choice depends on the scenario. Let's explore when to use each with real-world examples.
Imagine you run an online store. You have a Customers table and an Orders table. You want to see which customers have placed orders.
In this case, we use a JOIN because we need to combine data from two related tables.
Customers
| customer_id | first_name | last_name |
|---|---|---|
| 1 | Lian | Takahashi |
| 2 | Mateo | Lombardi |
| 3 | Anika | Sharma |
Orders
| order_id | customer_id | order_date |
|---|---|---|
| 101 | 1 | 2023-01-01 |
| 102 | 1 | 2023-01-15 |
| 103 | 2 | 2023-02-01 |
| 104 | 3 | 2023-03-01 |
Query Using JOIN
SELECT c.first_name, c.last_name, o.order_id, o.order_date
FROM Customers AS c
INNER JOIN Orders AS o
ON c.customer_id = o.customer_id;
Now, let's say you need a list of customers who haven't placed an order yet.
In this case, you can use a subquery to check if a customer ID exists in the Orders table.
Query Using Subquery
SELECT *
FROM Customers
WHERE customer_id NOT IN (
SELECT customer_id
FROM Orders
);
In this example, the subquery is used to calculate which customer IDs are associated with orders, and then the outer query filters out those customers, giving us only the customers who have not placed any orders.
| Factor | JOIN | Subquery |
| Purpose | Combines data from multiple tables | Filters or calculates data before retrieval |
| Performance | Faster,especially with indexed data | Slower in some cases |
| Readability | Can get complex with multiple tables | Simpler for filtering conditions |
| Flexibility | Works well for structured relationships | Ideal for aggregate-based filtering |
| Use Case | Retrieving related data (e.g., customers and orders) | Filtering based on conditions (e.g., customers older than average) |
By understanding both techniques, you can write efficient, optimized SQL queries that best fit your data needs.