I am unable to understand the concept of [Left Joins in SQL], can you explain me with a simple example
Sure! A LEFT JOIN in SQL is a type of join that returns all rows from the left-hand table (also known as the "LEFT" table), and any matching rows from the right-hand table (also known as the "RIGHT" table). If there is no match, NULL values are returned for right-hand table's columns.
Here is a simple example that demonstrates how a LEFT JOIN works:
Suppose we have two tables, customers
and orders
, with the following structure and data:
Customers:
id | name |
---|---|
1 | Alice |
2 | Bob |
3 | Eve |
Orders:
id | customer_id | product |
---|---|---|
1 | 1 | iPhone |
2 | 1 | MacBook |
3 | 2 | MacBook |
4 | 3 | iPhone |
5 | 3 | iMac |
Now, let's say we want to retrieve a list of all customers and their orders. We can use a LEFT JOIN to do this:
SELECT customers.name, orders.product
FROM customers
LEFT JOIN orders ON customers.id = orders.customer_id
This would return the following results:
name | product |
---|---|
Alice | iPhone |
Alice | MacBook |
Bob | MacBook |
Eve | iPhone |
Eve | iMac |
As you can see, the LEFT JOIN returns all rows from the customers
table, even if there are no matching rows in the orders
table. For customers who have no orders, the product
column is filled with NULL values.
I hope this helps! Let me know if you have any questions
Comments
Post a Comment