The LEFT OUTER JOIN or simply LEFT JOIN (you can omit the OUTER keyword in most databases), selects all the rows from the first table listed after the FROM clause, no matter if they have matches in the second table.If we slightly modify our last SQL statement to:
SELECT Customers.FirstName, Customers.LastName, SUM(Sales.SaleAmount) AS SalesPerCustomer FROM Customers LEFT JOIN Sales ON Customers.CustomerID = Sales.CustomerID GROUP BY Customers.FirstName, Customers.LastNameand the Sales table still has the following rows:
CustomerID | Date | SaleAmount |
2 | 5/6/2004 | $100.22 |
1 | 5/6/2004 | $99.95 |
The result will be the following:
FirstName | LastName | SalesPerCustomers |
John | Smith | $99.95 |
Steven | Goldfish | $100.22 |
Paula | Brown | NULL |
James | Smith | NULL |
As you can see we have selected everything from the Customers (first table). For all rows from Customers, which don’t have a match in the Sales (second table), the SalesPerCustomer column has amount NULL (NULL means a column contains nothing).
The RIGHT OUTER JOIN or just RIGHT JOIN behaves exactly as SQL LEFT JOIN, except that it returns all rows from the second table (the right table in our SQL JOIN statement).
No comments:
Post a Comment