The First Total: Mastering COUNT()
The Week Two Kickoff
The first week was about "Seeing" information. Now, in week two, the expectations have changed. My manager popped his head in: *"How many orders did we have last month?"*
He didn't want a list. He didn't want to scroll through 50,000 rows. He wanted *one number*. This is the moment I graduated from "Data Puller" to "Data Reporter."
The Quest: Aggregation
An **Aggregation** is any function that takes many rows and compresses them into a summary. Today's hero is `COUNT()`.
The Implementation: Counting the Universe
Counting All Rows
To get the total number of rows in a table, we use `COUNT(*)`.
-- How many orders do we have in total?
SELECT COUNT(*) AS total_orders
FROM orders;
Counting a Specific Column
If شما want to count only rows where a specific column has data (is not NULL), شما count the column itself.
-- How many orders have a shipping date recorded?
SELECT COUNT(shipping_date) AS shipped_orders
FROM orders;
Counting Unique Values
What if someone asks: *"How many different customers have ordered?"*
-- How many unique customers made purchases?
SELECT COUNT(DISTINCT customer_id) AS unique_customers
FROM orders;
The "Oops" Moment
Early on, I confused `COUNT(*)` with `COUNT(column)`. I reported that we had 50,000 shippable orders... but 5,000 of them had a NULL shipping date. The warehouse was very confused.
**Pro Tip**: `COUNT(*)` counts all rows. `COUNT(column)` only counts rows where that column isn't empty.
The Victory
The manager got his number in 0.5 seconds. He pasted it into a slide for the all-hands. I realized that executives don't want to see data—they want to see answers.
Your Task for Today
Count all rows in a table. Then, count a column that you know has some missing values. Compare the two results and understand why they differ.
*Day 17: The Money Metrics—SUM and AVG.*