Lessons › SQL › Chapter 3: Summarising
SQL lesson
COUNT(*), COUNT(column), COUNT(DISTINCT)
COUNT gives you three flavors of counting: every row no matter what, only rows where a specific field has a value (nulls don't count), or unique values only - so one person who shows up five times still counts as one.
Try this lesson free →Example
Counting Retail Orders, Discounts, and Unique Customers
SELECT COUNT(*) AS total_orders,
COUNT(discount) AS orders_with_discount,
COUNT(DISTINCT customer_id) AS unique_customers
FROM orders| total_orders | orders_with_discount | unique_customers |
|---|---|---|
| 5 | 3 | 3 |
Step by step
- Run the query without COUNT so you can see what the unfiltered values look like.
SELECT *, COUNT(discount) AS orders_with_discount, COUNT(DISTINCT customer_id) AS unique_customers FROM orders; - COUNT tells you how many rows match - perfect for sizing a table.
SELECT COUNT(*), COUNT(discount) AS orders_with_discount, COUNT(DISTINCT customer_id) AS unique_customers FROM orders; - AS gives the COUNT result a friendly column name so the output reads cleanly.
SELECT COUNT(*) AS total_orders, COUNT(discount) AS orders_with_discount, COUNT(DISTINCT customer_id) AS unique_customers FROM orders;
Practice
1. Using orders, write a query to count how many rows are in the table.
SELECT COUNT(*) FROM orders2. Using store_sales, write a query to count how many unique values are in the sale_id column.
SELECT COUNT(DISTINCT sale_id) FROM store_sales3. Using products, write a query to count how many rows are in the table.
SELECT COUNT(*) FROM products4. Using reviews, write a query to count how many non-null values are in the customer_id column.
SELECT COUNT(customer_id) FROM reviews5. Using employees, write a query to count how many unique values are in the full_name column.
SELECT COUNT(DISTINCT full_name) FROM employeesLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →