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:

const query: string = [
  "SELECT SUM(quantity),",
  "MAX(unit_price)",
  "FROM order_items",
].join(" ");

A long list of columns can go on over several strings. Inside the SQL, put a comma between two columns and none after the last one, or SQLite waits for one more column. The comma after each string is TypeScript's: it separates the items of the array, and .join(" ") joins them into one query. 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 in the first string, MIN and MAX in the second, then take them FROM the products table.


Hint
Each function takes the column's name in its parentheses. The SQL of the first string ends with a comma, inside the quotes; the second one doesn't, because it holds the last column. The comma after each string belongs to the array.


STEP 1 OF 3
    Ctrl + Enter to check