Beginner

595. JOIN with COUNT

Use COUNT with JOINs to measure related records.

📘 Lesson 605 of 728 ⏱ 13 min 🎯 Intermediate

COUNT can be used after a JOIN to determine how many related records exist for each entity.

Counting related records is one of the most common requirements in business analytics.

Count the number of orders placed by each customer.

SQL
SELECT
    c.CustomerName,
    COUNT(o.OrderID) AS OrderCount
FROM Customers c
LEFT JOIN Orders o
    ON c.CustomerID = o.CustomerID
GROUP BY
    c.CustomerName;

Used in customer activity, transaction monitoring, sales reporting, and operational dashboards.

  • COUNT can measure related rows.
  • COUNT(column) ignores NULL values.
  • LEFT JOIN preserves entities without matches.
  • GROUP BY defines the counting level.
  • COUNT(*) and COUNT(column) can produce different results.
Why use COUNT(o.OrderID) with LEFT JOIN?

COUNT(o.OrderID) counts only matching orders while still retaining customers with zero orders.

What is the difference between COUNT(*) and COUNT(column)?

COUNT(*) counts rows, while COUNT(column) counts only rows where that column is not NULL.

Have you finished this lesson?

Introduction to SQL – All Lessons