← All lessons
SQL from zero · Lesson 8 of 10

Calculations and names

A SELECT list can hold sums, not just columns. The database works the sum out for every row. Here is each price with 10% off:

SELECT name, price, price * 0.9
FROM products
WHERE category = 'Books';
Returns
name        | price | price * 0.9
------------+-------+------------
Field guide | 18    | 16.2
Sketchbook  | 9.75  | 8.775
(2 rows)

The signs are + and -, * for multiply and / for divide. Brackets work as in arithmetic.

price * 0.9 makes an ugly column heading. AS gives a result column a name of your choosing, called an alias. Names with spaces need double quotes, so most people use underscores instead. ROUND(x, 2) rounds to two decimal places:

SELECT name, ROUND(price * 1.08, 2) AS with_tax
FROM products
ORDER BY with_tax DESC
LIMIT 3;
Returns
name       | with_tax
-----------+---------
Binoculars | 129.6
Raincoat   | 63.72
Bird bath  | 49.14
(3 rows)

You can sort by an alias, as above. In most databases you can't use it in WHERE, though, because WHERE runs before the SELECT list is worked out (SQLite is unusually forgiving here). Repeat the sum in WHERE instead.

One trap: dividing one whole number by another gives a whole number in SQLite, PostgreSQL and SQL Server. The part after the point is thrown away:

SELECT 7 / 2 AS whole, 7 / 2.0 AS exact;
Returns
whole | exact
------+------
3     | 3.5
(1 row)

Make one side a decimal (2.0, or multiply by 1.0) when you want the exact answer. MySQL is the odd one out and gives 3.5 either way. (A SELECT with no FROM, like this one, just works out the values; it's handy for trying things.)

Practice

Each product's name and its price with 10% off (the price times 0.9).

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

+ - * /Add, subtract, multiply, divide.
expr AS nameName a result column (an alias).
ROUND(x, 2)Round to two decimal places.
7 / 2 vs 7 / 2.0Whole numbers divide to a whole number (3); add .0 for 3.5.

The other AI and data engineering courses