SQL Left Join
The LEFT JOIN keyword in SQL is used to retrieve rows from two or more tables. It returns all rows from the left table and the matched rows from the right table. If there is no match, the result is NULL on the side of the right table.
Syntax
The basic syntax for a LEFT JOIN is:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
Example
Consider two tables: Customers
and Orders
. To retrieve a list of all customers along with their orders, including customers who have not placed any orders, you can use the following query:
SELECT Customers.name, Orders.order_id
FROM Customers
LEFT JOIN Orders
ON Customers.id = Orders.customer_id;
Explanation
- SELECT columns: Specifies the columns to retrieve from the tables.
- FROM table1: Indicates the primary (left) table from which to retrieve data.
- LEFT JOIN table2: Specifies the secondary (right) table to join with the left table.
- ON table1.column = table2.column: Defines the condition for the join, i.e., the common column between the two tables.