Joins in SQL helps to combine rows of different tables based on a common column.
Customer ID | Name |
---|
1 | Alice |
2 | Bob |
3 | Charlie |
Order ID | Customer ID | Product |
---|
101 | 4 | Laptop |
102 | 2 | Phone |
103 | 5 | Laptop |
INNER JOIN returns matching rows from both tables.
SELECT Customers.CustomerID, Customers.Name, Orders.OrderID, Orders.Product
FROM Customers
INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
Customer ID | Name | Order ID | Product |
---|
2 | Bob | 102 | Phone |
LEFT JOIN returns all rows from the left table and matching rows from the right (NULL if no match)
SELECT Customers.CustomerID, Customers.Name, Orders.OrderID, Orders.Product
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
Customer ID | Name | Order ID | Product |
---|
1 | Alice | NULL | NULL |
2 | Bob | 102 | Phone |
3 | Charlie | NULL | NULL |
RIGHT JOIN returns all rows from the right table and matching rows from the left (NULL if no match)
SELECT Customers.CustomerID, Customers.Name, Orders.OrderID, Orders.Product
FROM Customers
RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
Customer ID | Name | Order ID | Product |
---|
4 | NULL | 101 | Laptop |
2 | Bob | 102 | Phone |
5 | NULL | 103 | Laptop |