In SQL, a LEFT JOIN
is used to combine rows from two tables based on a related column, but it returns all the rows from the left table (the first table), along with the matching rows from the right table (the second table). If there is no match, the result will contain NULL
for the columns of the right table.
Syntax:
sql
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
Example:
Assume we have two tables:
- Customers
customer_id customer_name 1 John Doe 2 Jane Smith 3 Alice Johnson - Orders
order_id customer_id order_date 101 1 2025-01-01 102 2 2025-01-02
Query:
sql
SELECT Customers.customer_id, Customers.customer_name, Orders.order_id, Orders.order_date
FROM Customers
LEFT JOIN Orders
ON Customers.customer_id = Orders.customer_id;
Result:
customer_id | customer_name | order_id | order_date |
---|---|---|---|
1 | John Doe | 101 | 2025-01-01 |
2 | Jane Smith | 102 | 2025-01-02 |
3 | Alice Johnson | NULL | NULL |
In this example, the query returns all customers, including Alice Johnson who did not place any order (hence, NULL
values for the order columns).