Bird
Raised Fist0
MySQLquery~5 mins

JOIN with aggregate functions in MySQL

Choose your learning style10 modes available
Introduction
We use JOIN with aggregate functions to combine data from two tables and then calculate totals, averages, or counts on the combined data.
You want to find the total sales for each customer by combining customer and sales tables.
You need to count how many orders each product has by joining products and orders tables.
You want to calculate the average rating for each movie by joining movies and reviews tables.
Syntax
MySQL
SELECT columns, AGGREGATE_FUNCTION(column)
FROM table1
JOIN table2 ON table1.common_column = table2.common_column
GROUP BY columns;
AGGREGATE_FUNCTION can be SUM, COUNT, AVG, MAX, MIN.
GROUP BY is needed to group rows before applying the aggregate function.
Examples
Counts how many orders each customer has.
MySQL
SELECT customers.name, COUNT(orders.id) AS order_count
FROM customers
JOIN orders ON customers.id = orders.customer_id
GROUP BY customers.name;
Calculates total quantity sold for each product.
MySQL
SELECT products.name, SUM(order_items.quantity) AS total_sold
FROM products
JOIN order_items ON products.id = order_items.product_id
GROUP BY products.name;
Finds average salary per department.
MySQL
SELECT employees.department, AVG(salaries.amount) AS avg_salary
FROM employees
JOIN salaries ON employees.id = salaries.employee_id
GROUP BY employees.department;
Sample Program
This query joins customers with their orders, counts how many orders each customer made, and sums the total amount spent.
MySQL
CREATE TABLE customers (
  id INT PRIMARY KEY,
  name VARCHAR(50)
);

CREATE TABLE orders (
  id INT PRIMARY KEY,
  customer_id INT,
  amount DECIMAL(10,2),
  FOREIGN KEY (customer_id) REFERENCES customers(id)
);

INSERT INTO customers VALUES (1, 'Alice'), (2, 'Bob');
INSERT INTO orders VALUES (1, 1, 100.00), (2, 1, 50.00), (3, 2, 75.00);

SELECT customers.name, COUNT(orders.id) AS order_count, SUM(orders.amount) AS total_amount
FROM customers
JOIN orders ON customers.id = orders.customer_id
GROUP BY customers.name;
OutputSuccess
Important Notes
Always use GROUP BY when using aggregate functions with JOIN to group results correctly.
JOIN combines rows from two tables based on a related column.
Aggregate functions summarize data, like counting or summing values.
Summary
JOIN with aggregate functions helps combine and summarize data from multiple tables.
Use GROUP BY to group data before applying aggregate functions.
Common aggregate functions include COUNT, SUM, and AVG.

Practice

(1/5)
1. What does the following SQL query do?
SELECT department, COUNT(employee_id) FROM employees JOIN departments ON employees.dept_id = departments.id GROUP BY department;
easy
A. Counts employees in each department by joining employees and departments tables.
B. Lists all employees without grouping by department.
C. Calculates the average salary per department.
D. Deletes employees who are not assigned to any department.

Solution

  1. Step 1: Understand the JOIN operation

    The query joins the employees and departments tables using the department ID to combine related data.
  2. Step 2: Analyze the GROUP BY and COUNT

    It groups the results by department and counts the number of employees in each group.
  3. Final Answer:

    Counts employees in each department by joining employees and departments tables. -> Option A
  4. Quick Check:

    JOIN + GROUP BY + COUNT = Employee count per department [OK]
Hint: JOIN tables, GROUP BY key, then apply COUNT [OK]
Common Mistakes:
  • Ignoring GROUP BY causes wrong aggregation
  • Using COUNT without JOIN returns incomplete data
  • Confusing COUNT with SUM or AVG
2. Which of the following is the correct syntax to get the total sales per customer using JOIN and SUM?
SELECT customers.name, SUM(orders.amount) FROM customers JOIN orders ON customers.id = orders.customer_id GROUP BY customers.name;
easy
A. SELECT customers.name, SUM(orders.amount) FROM customers LEFT JOIN orders GROUP BY customers.name;
B. SELECT customers.name, SUM(orders.amount) FROM customers JOIN orders WHERE customers.id = orders.customer_id GROUP BY customers.name;
C. SELECT customers.name, SUM(orders.amount) FROM customers JOIN orders ON customers.id = orders.customer_id GROUP BY customers.name;
D. SELECT customers.name, SUM(orders.amount) FROM customers, orders GROUP BY customers.name;

Solution

  1. Step 1: Check JOIN syntax

    SELECT customers.name, SUM(orders.amount) FROM customers JOIN orders ON customers.id = orders.customer_id GROUP BY customers.name; uses correct INNER JOIN syntax with ON clause to link customers and orders.
  2. Step 2: Verify GROUP BY and SUM usage

    SELECT customers.name, SUM(orders.amount) FROM customers JOIN orders ON customers.id = orders.customer_id GROUP BY customers.name; correctly groups by customer name and sums order amounts.
  3. Final Answer:

    SELECT customers.name, SUM(orders.amount) FROM customers JOIN orders ON customers.id = orders.customer_id GROUP BY customers.name; -> Option C
  4. Quick Check:

    JOIN with ON + GROUP BY + SUM = Correct syntax [OK]
Hint: Use JOIN ... ON ... with GROUP BY for aggregates [OK]
Common Mistakes:
  • Using WHERE instead of ON in JOIN
  • Missing ON clause causes syntax error
  • Grouping by wrong column
3. Given tables:
employees(id, name, dept_id)
departments(id, department)
What is the output of this query?
SELECT d.department, COUNT(e.id) AS emp_count FROM employees e LEFT JOIN departments d ON e.dept_id = d.id GROUP BY d.department ORDER BY emp_count DESC;
medium
A. Syntax error due to missing GROUP BY column.
B. List of departments with employee counts, including departments with zero employees.
C. List of employees with their department names.
D. List of departments with employee counts, excluding departments with zero employees.

Solution

  1. Step 1: Understand LEFT JOIN effect

    FROM employees e LEFT JOIN departments d ON e.dept_id = d.id includes all employees and matching departments if they exist. Departments with no employees do not appear because no employee row matches them.
  2. Step 2: GROUP BY and COUNT behavior

    Grouping by d.department counts employees only for departments that have at least one employee (count >=1). Departments with zero employees are excluded.
  3. Final Answer:

    List of departments with employee counts, excluding departments with zero employees. -> Option D
  4. Quick Check:

    LEFT JOIN from employees + GROUP BY department excludes zero counts [OK]
Hint: LEFT JOIN keeps all left rows, COUNT counts matches [OK]
Common Mistakes:
  • Assuming INNER JOIN behavior excludes zero counts
  • Confusing COUNT(*) with COUNT(column)
  • Ignoring NULL values in grouping
4. Identify the error in this query:
SELECT d.department, COUNT(e.id) FROM employees e JOIN departments d ON e.dept_id = d.id WHERE e.salary > 50000 GROUP BY e.dept_id;
medium
A. GROUP BY should use d.department instead of e.dept_id.
B. Missing HAVING clause for salary filter.
C. COUNT(e.id) cannot be used with JOIN.
D. ON clause is incorrect syntax.

Solution

  1. Step 1: Check GROUP BY columns

    The SELECT lists d.department but GROUP BY uses e.dept_id, causing mismatch.
  2. Step 2: Fix GROUP BY to match SELECT

    GROUP BY should use d.department or include it to avoid errors.
  3. Final Answer:

    GROUP BY should use d.department instead of e.dept_id. -> Option A
  4. Quick Check:

    GROUP BY columns must match SELECT non-aggregates [OK]
Hint: GROUP BY columns must match SELECT non-aggregates [OK]
Common Mistakes:
  • Grouping by wrong or missing columns
  • Using WHERE instead of HAVING for aggregates
  • Incorrect JOIN ON syntax
5. You have tables:
orders(order_id, customer_id, amount)
customers(customer_id, name)
Write a query to find customers who have total orders amount greater than 1000, including customers with no orders showing zero total.
Which query is correct?
hard
A. SELECT c.name, SUM(o.amount) AS total FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id WHERE total > 1000 GROUP BY c.name;
B. SELECT c.name, COALESCE(SUM(o.amount), 0) AS total FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id GROUP BY c.name HAVING total > 1000;
C. SELECT c.name, SUM(o.amount) AS total FROM customers c JOIN orders o ON c.customer_id = o.customer_id GROUP BY c.name HAVING total > 1000;
D. SELECT c.name, SUM(o.amount) AS total FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id GROUP BY c.name WHERE total > 1000;

Solution

  1. Step 1: Use LEFT JOIN to include customers without orders

    LEFT JOIN ensures all customers appear, even if no matching orders exist.
  2. Step 2: Use COALESCE to convert NULL sums to zero and HAVING to filter totals

    COALESCE replaces NULL with 0; HAVING filters groups by aggregate result.
  3. Final Answer:

    SELECT c.name, COALESCE(SUM(o.amount), 0) AS total FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id GROUP BY c.name HAVING total > 1000; -> Option B
  4. Quick Check:

    LEFT JOIN + COALESCE + HAVING filters totals correctly [OK]
Hint: Use LEFT JOIN + COALESCE + HAVING for conditional aggregates [OK]
Common Mistakes:
  • Using WHERE instead of HAVING for aggregate filters
  • Ignoring NULL sums for customers without orders
  • Using INNER JOIN excludes customers with zero orders
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard