In SQL, COUNT is a super handy function when you want to know how many rows you've got in a column. It's like asking, "Hey, how many entries are here?".
Suppose we have a table named orders with the following columns and sample data:
| order_id | product_id | quantity | product_name |
|---|---|---|---|
| 1 | 101 | 2 | Espresso |
| 2 | 102 | 1 | Cappuccino |
| 3 | 103 | 1 | Blueberry Muffin |
| 4 | 104 | 3 | Latte |
| 5 | 101 | 2 | Espresso |
| 6 | 105 | 1 | Chocolate Chip Muffin |
| 7 | 103 | 2 | Blueberry Muffin |
| 8 | 102 | 1 | Cappuccino |
| 9 | 106 | 1 | Bagel |
| 10 | 104 | 2 | Latte |
Count Total Orders: This query counts the total number of orders in the orders table.
SELECT COUNT(*)
FROM orders;
Count Specific Product Orders: This query counts how many orders were placed for 'Espresso'.
SELECT COUNT(*)
FROM orders
WHERE product_name = 'Espresso';
Count with Column Alias: This query counts the total orders and labels the result as total_orders for clarity. We will that alias trick a lot!
SELECT COUNT(*) AS total_orders
FROM orders;
Let's look at a sample of our table again. As you can see below, you can have multiple orders from the same product_id.
| order_id | product_id | quantity | product_name |
|---|---|---|---|
| 1 | 101 | 2 | Espresso |
| 2 | 102 | 1 | Cappuccino |
| 3 | 103 | 1 | Blueberry Muffin |
| 4 | 104 | 3 | Latte |
Here you can see that order_id numbers 1 and 5 bought an Espresso and you have been asked to count the number of unique products. This is when DISTINCT comes in, and you need to specify which column you want to get the unique value from (in this case product_id).
This is how it looks in SQL:
SELECT COUNT(DISTINCT product_id) AS unique_products
FROM orders;
See I used the alias again and called it unique_products. This will help when you handle long queries to give a name to your columns.
Great job in finishing this section!
Time to practice!
| 5 |
| 101 |
| 2 |
| Espresso |