SQL COUNT & SUM Functions 🧮¶
Mentor's Note:
COUNTandSUMare the most basic reporting tools.COUNTtells you "How many?" andSUMtells you "How much?" 💡
🌟 The Scenario: The T-Shirt Shop 👕¶
Imagine you are managing an inventory. - COUNT: "How many orders did we receive today?" (The number of rows). 📦 - SUM: "What was the total money earned from those orders?" (The sum of the 'Price' column). 💰
💻 1. The COUNT() Function¶
Counts the number of records in a set.
A. COUNT(*) vs COUNT(column)¶
COUNT(*): Counts every row, including those with NULL values.COUNT(column): Counts only the rows where that specific column is NOT NULL.
-- Scenario: Total number of records
SELECT COUNT(*) FROM orders;
-- Scenario: Count people who have an email registered
SELECT COUNT(email) FROM customers;
B. COUNT(DISTINCT)¶
Counts unique values only.
💻 2. The SUM() Function¶
Adds up all the numeric values in a column.
-- Scenario: Total revenue for February
SELECT SUM(total_price)
FROM orders
WHERE order_date BETWEEN '2026-02-01' AND '2026-02-28';
🎨 Visual Logic: Count vs Sum¶
| Order ID | Product | Qty |
|---|---|---|
| 1 | Pen | 10 |
| 2 | Pencil | 20 |
| 3 | Notebook | NULL |
- COUNT(Qty) = 2 (Ignores the NULL)
- SUM(Qty) = 30 (10 + 20)