Start learning free

LESSON 49 OF 173 · BACKEND: SQL

Name Columns with AS in Java

Practice

A column in your answer doesn't have to be stored in the table. SELECT can compute one from other columns, row by row: price * stock is what all the items of a product are worth together.

A computed column is named after its expression, which makes a clumsy header. AS gives it a name you choose, an alias. For example, the prices in cents:

String query = "";
query += "SELECT name, price * 100 AS cents ";
query += "FROM products ";

Multiplying by a decimal number can leave a long tail of digits. ROUND keeps just a few: ROUND(2.345678, 2) is 2.35, two digits after the point. And once a column has an alias, ORDER BY can sort by that name, without repeating the math.

Your query must print each product's name, its stock value and its price with an 8% tax, the biggest stock value first:

name | stock_value | price_with_tax
Gift card | 49950 | 54
Pen | 240 | 2.16
Stapler | 135 | 9.72
Mug | 120 | 12.96
Plant | 90 | 16.2
Teapot | 88 | 23.76
Lamp | 29 | 31.32
Notebook | 0 | 7.56
(8 rows)

Your task: the starting code already connects db to shop.db and starts query as an empty string. Below it, with query +=, select name, price * stock named stock_value, and price * 1.08 rounded to 2 digits named price_with_tax, from products, sorted by stock_value from biggest to smallest.


Assignment
Follow the Coding Tutorial to write the query one clause at a time: the two computed columns with their aliases, then FROM and ORDER BY.


Hint
The first string ends with a comma and a space, because the ROUND column follows on the next line. The 2 goes inside ROUND's parentheses, after a comma. DESC sorts from big to small.


STEP 1 OF 4
    Ctrl + Enter to check

    Sql Aliases 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