SQL

Lesson 4 of 10

Lesson ยท 10 min

Count and calculate

One answer from many rows

An aggregate function reads many rows and gives one value.

Function Result
COUNT(*) the number of rows
SUM(column) the total of the values
AVG(column) the average of the values
MIN(column) the smallest value
MAX(column) the largest value
SELECT COUNT(*) FROM books;
SELECT AVG(price) FROM books;

The result of an aggregate query has one row.

Names for columns

The column of COUNT(*) has a long name that is hard to read. Use AS to give the column a better name. This is called an alias.

SELECT COUNT(*) AS book_count FROM books;

Filter first, then calculate

WHERE runs before the aggregate function. Only the rows that match are counted or added.

SELECT SUM(price) AS fantasy_total FROM books WHERE genre = 'Fantasy';

Rounding

ROUND(value, digits) rounds a number. Averages often have many decimals, so rounding makes them easier to read.

SELECT ROUND(AVG(price), 1) AS average_price FROM books;

Your turn

Write one query for each task, one after the other. Use the column names that the tasks ask for.

Tasks

5 to do

  1. Task 1, not checked yet. Count the books. Use COUNT(*) and give the column the name total_books.

  2. Task 2, not checked yet. Find the lowest and the highest price. Name the columns lowest_price and highest_price. Use MIN and MAX.

  3. Task 3, not checked yet. Find the average price, rounded to 2 decimals. Name the column average_price. Use AVG and ROUND.

  4. Task 4, not checked yet. Find the total price of the Mystery books. Name the column mystery_total. Use SUM and WHERE.

  5. Task 5, not checked yet. Count the books from 2019 or later. Name the column recent_books.

Task 1 of 5

Count the books. Use COUNT(*) and give the column the name total_books.

All tasks

query.sql

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.