Module 01 · lesson 4
Expressions and calculations in SELECT
Marketing is launching a "−10% on everything" promotion. You need to show the discounted price without changing the actual prices in the database.
SELECT can do math
In SELECT you can not only take ready-made columns but also compute new ones. Ordinary arithmetic is available: +, -, *, /. The general form of a computed column:
SELECT <calculation> AS <column_name>
FROM <table>;
For example, let's compute the value of each product's whole stock (price × quantity in stock):
SELECT name, price * stock AS stock_value
FROM products;
The new column exists only in the DBMS's response — the data itself doesn't change. Without an alias (AS), Postgres names it unreadably (?column?), so always give it a name.
Calculating the discount
A "−10%" discount means that 90% of the price remains. And 90% is the multiplier 0.9. So the discounted price = the price multiplied by 0.9.
Your turn
Output name, price, and the discounted price under the name price_sale (price * 0.9).
Summary
SELECTcan do math: arithmetic expressions (+ - * /) create new columns.- Computed columns exist only in the response — the table doesn't change.
- Always give a computation a name with
AS.