Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Method One
Method Two
5. Method 2 – explanation
Method Three


Very well done! Let's move on to method two. This method shows different groups in separate columns.

Let's say we want to count the number of orders already shipped and the number of orders not yet shipped:

orders_shipped orders_pending
809 21

Take a look at the query:

    WHEN shipped_date IS NOT NULL
      THEN order_id
  END) AS orders_shipped,
    WHEN shipped_date IS NULL
      THEN order_id
  END) AS orders_pending
FROM orders;

In this technique, we use multiple COUNT(CASE WHEN...) or SUM(CASE WHEN...) statements in the query. Each statement is used to show the metric for a single group in a new column. We also need to name each column using the X AS alias construction.

In Method 1, groups were represented as rows and created with a single CASE WHEN statement. Here, they are represented as columns and created with separate aggregate function invocations. This is why Method 2 is typically a good choice for a small number of groups.


Count the number of vegetarian and non-vegetarian products. Show two columns: non_vegetarian_count and vegetarian_count.

Hint: Non-vegetarian products have a category_id of 6 or 8.

Stuck? Here's a hint!

You can count non-vegetarian products in the following way:

  WHEN category_id IN (6, 8)
    THEN product_id