← SQL and databases

Calculated columns and names with AS

Do math in a query and give results clear names.

Start this lesson

A SELECT can calculate new values from columns with + , - , * and /. For example price * stock is how much the stock on the shelf is worth. AS gives the new column a name, so the result is easy to read. You can also join text with ||: first || ' ' || last.

SELECT name, price * stock AS stock_value
FROM products;

For every product, multiplies its price by how many are in stock and calls the result stock_value.

Careful with division: in SQLite, dividing two whole numbers gives a whole number. 7 / 2 is 3, not 3.5. Write 7 / 2.0 or 7 * 1.0 / 2 to get 3.5.

ROUND(x, 2) rounds x to 2 decimal places, which is nice for money.