Start learning free

LESSON 49 OF 173 · BACKEND: SQL

Name Columns with AS

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:

var query = "SELECT name, price * 100 AS cents " +
	"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. Below it, declare query as string pieces joined with +: 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 piece ends with a comma inside the quotes, because the ROUND column follows in the next piece. The 2 goes inside ROUND's parentheses, after a comma. DESC sorts from big to small. Every piece but the last ends with +.


STEP 1 OF 4
    Ctrl + Enter to check