BBampaa

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 →
About 5–10 minutes · no sign-up needed

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

Result:

total_ordersorders_with_discountunique_customers
533

Step by step

  1. 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;
  2. 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;
  3. 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

Try each one in your head first, then open the answer.

1. Using orders, write a query to count how many rows are in the table.
SELECT COUNT(*) FROM orders
2. 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_sales
3. Using products, write a query to count how many rows are in the table.
SELECT COUNT(*) FROM products
4. Using reviews, write a query to count how many non-null values are in the customer_id column.
SELECT COUNT(customer_id) FROM reviews
5. Using employees, write a query to count how many unique values are in the full_name column.
SELECT COUNT(DISTINCT full_name) FROM employees

Learn 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 →
About 5–10 minutes · no sign-up needed