Start learning free

LESSON 46 OF 173 · BACKEND: SQL

SUM, AVG, MIN, MAX

Practice

COUNT is one of the aggregate functions: functions that turn all the rows into a single value. Four more work on a column of numbers: SUM adds it up, AVG gives its average, MIN its smallest value and MAX its largest.

You can select several of them in one query. For example, this prints how many items were ordered in total and the highest unit price ever paid:

var query = "SELECT SUM(quantity), " +
	"MAX(unit_price) " +
	"FROM order_items "

A long list of columns can go on over several lines. Put a comma between two columns and none after the last one, or SQLite waits for one more column. AVG divides, so its answer is a decimal number. For the shop's products, the check prints your query's result, which must be:

SUM(stock) | AVG(price) | MIN(price) | MAX(price)
1155 | 18.25 | 2 | 50
(1 row)

Your task: in one query, find how many items the shop has in stock in total, the average price of its products, and the lowest and the highest price.


Assignment
Follow the Coding Tutorial to select SUM and AVG on the first line, MIN and MAX on the second, then take them FROM the products table.


Hint
Each function takes the column's name in its parentheses. The first line of columns ends with a comma inside the string; the second one doesn't, because it holds the last column. Every string piece but the last ends with +.


STEP 1 OF 3
    Ctrl + Enter to check