Skip to main content

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:

idname
1Alice
2Bob
3Eve

Orders:

idcustomer_idproduct
11iPhone
21MacBook
32MacBook
43iPhone
53iMac

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:

nameproduct
AliceiPhone
AliceMacBook
BobMacBook
EveiPhone
EveiMac

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