Doing Maths in SELECT
New columns from old ones.
Helen asks, how much money is sitting on my shelves? For each book, that's the price, times the number in stock. There's no column for that. But SQL can calculate it for you, on every row.

- Money sitting on the shelves
- Price times stock
- Calculate it on every row
A calculated column
You can put a calculation right after select, like price times stock. SQL works it out for each row. Run it. It works, but look at the column heading. It's just the formula, price star stock. That's not very friendly.
SELECT title, price * stock
FROM books
LIMIT 3;โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ โ title โ price * stock โ โโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโค โ The Silent Orchard โ 869.42 โ โ Code of the River โ 337.74 โ โ Stars Over Lagos โ 469.53 โ โโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโ
Give it a name with AS
To give a column a friendly name, add as, and then the name you want. This is called an alias. Now we can also sort by that name. Run it. SQL in a Weekend holds the most money on the shelves, at almost thirteen hundred dollars.
SELECT title, price * stock AS stock_value
FROM books
ORDER BY stock_value DESC
LIMIT 3;โโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโ โ title โ stock_value โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโค โ SQL in a Weekend โ 1289.57 โ โ A Short History of Bread โ 1059.47 โ โ Numbers Don't Lie โ 1033.53 โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโ
Maths signs
Here are the maths signs you can use. Plus and minus. A star for multiply, and a slash for divide. And the percent sign, which gives the remainder after dividing. Just like a calculator.
| key | value |
|---|---|
| + - | add, subtract |
| * | multiply |
| / | divide |
| % | remainder |
Summary
You can calculate new columns, and name them with as. Next, rounding, and a small surprise with division.
Key takeaways- Calculate in SELECT
- AS gives a friendly name
- + - * / %