BBampaa

Lessons › SQL › Chapter 3: Summarising

SQL lesson

COUNT(*), COUNT(column), COUNT(DISTINCT)

COUNT(*) counts every row. COUNT(discount) counts only the rows where discount has a value. COUNT(DISTINCT customer_id) counts each customer once, however many orders they placed.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Three ways to count

SELECT COUNT(*) AS orders
FROM orders

Result:

orders
5

Step by step

  1. Counts all the rows.
    SELECT COUNT(*) AS total_orders, COUNT(discount) AS orders_with_discount, COUNT(DISTINCT customer_id) AS unique_customers FROM orders
  2. Counts only rows where discount has a value.
    SELECT COUNT(*) AS total_orders, COUNT(discount) AS orders_with_discount, COUNT(DISTINCT customer_id) AS unique_customers FROM orders
  3. Counts each customer once, however many orders they have.
    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 products, write a query to count how many rows are in the table.
SELECT COUNT(*) FROM products

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