Start learning free

LESSON 46 OF 173 · BACKEND: SQL

SUM, AVG, MIN, MAX in Java

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:

String query = "";
query += "SELECT SUM(quantity), ";
query += "MAX(unit_price) ";
query += "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 add SUM and AVG to query 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 string of columns ends with a comma; the second one doesn't, because it holds the last column. End each string with a space inside the quotes.


STEP 1 OF 3
    Ctrl + Enter to check

    Sql Aggregates in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free