Instruction
Perfect! When writing reports in SQL, you have to remember that some objects may not exist. In this exercise we discuss a very common error in using COUNT() with LEFT JOIN. The next report we'd like to create should count orders for three different customer IDs: N'ALFKI', N'FISSA', and N'PARIS':
SELECT C.CustomerID, COUNT(O.OrderID) AS OrderCount FROM Customers C LEFT JOIN Orders O ON O.CustomerID = C.CustomerID WHERE C.CustomerID IN (N'ALFKI', N'FISSA', N'PARIS') GROUP BY C.CustomerID;
Note the following:
- We used
LEFT JOINto make sure we'll see all three customer IDs in the report. If we used a simpleJOINand any of the customers placed no orders, they would not be shown in the report. - We used
COUNT(O.OrderID)instead ofCOUNT(*). This ensures that we only count rows with non-NULLOrderIDcolumn values. This is important if a customer hasn't ordered anything – in that case,COUNT(*)would return1instead of0because there would be one row with the givenCustomerIDand aNULLvalue in theOrderIDcolumn.
Exercise
Find the total number of products provided by each supplier. Show the CompanyName and ProductsCount (the number of products supplied) columns. Include suppliers that haven't provided any products.
Stuck? Here's a hint!
Use a LEFT JOIN on the Suppliers and Products tables. Remember to include the SupplierID in the GROUP BY clause.




