Lesson 3 of 8 · Structured Query Language (SQL)

Summarizing and Joining Data

How to total and count with aggregate functions, group rows with GROUP BY and HAVING, combine tables with joins, and nest one query inside another.

Beginner 8 sections 7 min read

Aggregate functions

The previous lesson returned rows one by one. Real questions are often about totals ("How much did we sell?") or need data from more than one table ("Which customer placed this order?"). This lesson covers both.

Aggregate functions take many rows and return one value:

FunctionReturnsOn all six sample orders
COUNT(*)The number of rows6
SUM(amount)The total1970.5
AVG(amount)The average328.42 (rounded)
MIN(amount)The smallest value40
MAX(amount)The largest value1200
SELECT COUNT(*)              AS orders,
       SUM(amount)           AS total,
       ROUND(AVG(amount), 2) AS average
FROM   sales.orders
WHERE  status <> 'CANCELLED';

    ORDERS      TOTAL    AVERAGE
---------- ---------- ----------
         5     1930.5      386.1

Grouping rows with GROUP BY

GROUP BY splits the rows into groups that share a value, then runs the aggregate functions once per group. Instead of one total, you get one total per customer:

ORDERS ONE ROW PER CUSTOMER 101250 10275.5 1031200 10440 105310 10695 121 321 GROUP BY customer_id 123 3 orders2 orders1 order 1545385.540
The circles show each order's customer_id. Orders with the same customer end up in the same group.
SELECT   customer_id,
         COUNT(*)    AS orders,
         SUM(amount) AS total
FROM     sales.orders
GROUP BY customer_id
ORDER BY total DESC;

CUSTOMER_ID     ORDERS      TOTAL
----------- ---------- ----------
          1          3       1545
          2          2      385.5
          3          1         40

3 rows selected.

The rule for GROUP BY: every column in SELECT must either be in the GROUP BY list or be inside an aggregate function. Otherwise the database can't know which of the group's values to show:

SELECT customer_id, status, COUNT(*) FROM sales.orders GROUP BY customer_id;
ORA-00979: not a GROUP BY expression

Filtering groups with HAVING

WHERE filters rows before they're grouped. HAVING filters groups after, so it can use aggregate functions. This query finds customers with at least two orders:

SELECT   customer_id, COUNT(*) AS orders
FROM     sales.orders
GROUP BY customer_id
HAVING   COUNT(*) >= 2;

CUSTOMER_ID     ORDERS
----------- ----------
          1          3
          2          2

2 rows selected.

With all the clauses together, this is the order the database runs them in:

FROM WHERE GROUP BY HAVING SELECT ORDER BY pick tablesfilter rowsmake groups filter groupspick columnssort

You can use both in one query. Here, cancelled orders are removed first, then only customers with two or more remaining orders are kept:

SELECT   customer_id, COUNT(*) AS orders, SUM(amount) AS total
FROM     sales.orders
WHERE    status <> 'CANCELLED'
GROUP BY customer_id
HAVING   COUNT(*) >= 2;

CUSTOMER_ID     ORDERS      TOTAL
----------- ---------- ----------
          1          3       1545
          2          2      385.5

2 rows selected.

Joining tables

The orders table stores customer_id, not the customer's name. That's on purpose: each fact is stored once, so a customer's name lives only in the customers table. To show orders with names, you join the two tables, matching rows where the customer_id values are equal:

CUSTOMERS ORDERS 1 Kofi 2 Ama 3 Yaw 4 Esi 5 Kwame 101 cust 1 102 cust 2 103 cust 1 104 cust 3 105 cust 2 106 cust 1 no orders no orders ON o.customer_id = c.customer_id

INNER JOIN: only the matches

A plain JOIN (short for INNER JOIN) returns one row for each matching pair. c and o are table aliases: short names that save typing and make clear which table each column comes from.

SELECT   c.name, o.order_id, o.amount
FROM     sales.customers c
JOIN     sales.orders o ON o.customer_id = c.customer_id
ORDER BY o.order_id;

NAME         ORDER_ID     AMOUNT
---------- ---------- ----------
Kofi              101        250
Ama               102       75.5
Kofi              103       1200
Yaw               104         40
Ama               105        310
Kofi              106         95

6 rows selected.

Esi and Kwame don't appear: they have no orders, so there's nothing to match.

LEFT JOIN: keep every row from the first table

A LEFT JOIN (or LEFT OUTER JOIN) keeps every row from the table on the left, even without a match. The columns from the other table are filled with NULL:

SELECT   c.name, o.order_id, o.amount
FROM     sales.customers c
LEFT JOIN sales.orders o ON o.customer_id = c.customer_id
ORDER BY c.customer_id, o.order_id;

NAME         ORDER_ID     AMOUNT
---------- ---------- ----------
Kofi              101        250
Kofi              103       1200
Kofi              106         95
Ama               102       75.5
Ama               105        310
Yaw               104         40
Esi
Kwame

8 rows selected.

That makes LEFT JOIN the way to answer "who hasn't…?" questions. Adding WHERE o.order_id IS NULL to the query above returns just Esi and Kwame: the customers with no orders.

JoinReturns
JOIN (INNER JOIN)Only rows that match in both tables
LEFT JOINEvery row from the left table, plus matches from the right
RIGHT JOINEvery row from the right table, plus matches from the left
FULL JOINEvery row from both tables, matched where possible

Joining and grouping together

Joins and aggregates combine naturally. This query shows every customer's order count and total, including customers with no orders:

SELECT   c.name,
         COUNT(o.order_id)      AS orders,
         NVL(SUM(o.amount), 0)  AS total
FROM     sales.customers c
LEFT JOIN sales.orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
ORDER BY total DESC, c.name;

NAME           ORDERS      TOTAL
---------- ---------- ----------
Kofi                3       1545
Ama                 2      385.5
Yaw                 1         40
Esi                 0          0
Kwame               0          0

5 rows selected.
  • COUNT(o.order_id), not COUNT(*): Esi's row has a NULL order_id, so it counts 0. COUNT(*) would count Esi's row and wrongly show 1.
  • NVL(SUM(o.amount), 0) shows 0 instead of NULL for customers with nothing to add up.
  • Grouping by customer_id as well as name keeps two customers who share a name apart.

Subqueries

A subquery is a query inside another query, in parentheses. The inner query runs first, and its result is used by the outer one. Which customers have placed an order over 300?

SELECT name
FROM   sales.customers
WHERE  customer_id IN (SELECT customer_id
                       FROM   sales.orders
                       WHERE  amount > 300);

NAME
----------
Kofi
Ama

2 rows selected.

Read it from the inside out: the inner query finds the customer IDs with a big order (1 and 2), and the outer query shows those customers' names.

In practice: grouping and joining, DBA style

When a disk is filling up, the first question is "who's using the space?". GROUP BY answers it, from the DBA_SEGMENTS view that lists every table and index:

-- space used per schema, largest first, only schemas over 1 GB
SELECT owner, ROUND(SUM(bytes) / 1024 / 1024 / 1024, 1) AS gb
FROM   dba_segments
GROUP  BY owner
HAVING SUM(bytes) > 1024 * 1024 * 1024
ORDER  BY gb DESC;

When the database is busy, a join shows which SQL each active session is running, by matching sessions to the statements in the shared pool:

SELECT s.sid, s.username, q.sql_text
FROM   v$session s
JOIN   v$sql q ON q.sql_id = s.sql_id AND q.child_number = s.sql_child_number
WHERE  s.status = 'ACTIVE'
AND    s.username IS NOT NULL;

Key takeaways

  • Aggregate functions (COUNT, SUM, AVG, MIN, MAX) turn many rows into one value, and skip NULLs.
  • GROUP BY gives one result row per group. Every selected column must be grouped or aggregated.
  • WHERE filters rows before grouping; HAVING filters groups after.
  • Joins combine tables by matching keys. JOIN keeps only matches; LEFT JOIN keeps every row from the left table.
  • Always give a join its ON condition, or every row pairs with every other row.
  • A subquery is a query inside a query, read from the inside out.