Stop 02 · Basic SELECT QueriesTopics · 5/8

Calculated Columns and Arithmetic

Part of the SQL Roadmap

In short

Tables store raw facts like price and quantity. Most questions need something derived, like line totals, GST or discounts. SQL calculates these on the fly as it reads each row.

You can compute new values on the fly with + - * / and functions, such as price * quantity as line_total. The result appears as a column in the output but is not stored in the table.

The jaadu weighs a box of sweets on a shop scale while tapping numbers on a big desk calculator.

Think of it like this

The billing counter

At a mithai shop the counter staff weighs 0.5 kg kaju katli, multiplies by ₹1,200 per kg, adds GST and prints the bill. The price list on the wall never changes. A calculated column is that billing maths, done fresh for every row you read.

Watch it happen

One order line, worked out step by step

price 250
0
qty 3
1
line_total ?
2
discount ?
3
payable ?
4

1/5The table stores only price and quantity for this order line.

The big ideas

What you need to know

+ - * / and %

Standard maths works on numeric columns. % gives the remainder in PostgreSQL and MySQL.

Integer division trap

In PostgreSQL and SQL Server, 7 / 2 is 3. Use 7 / 2.0 or cast to NUMERIC to keep decimals. MySQL gives 3.5000.

Brackets set the order

* and / happen before + and -. Use brackets so the maths reads the way you mean it.

NULL spreads

price * NULL is NULL. One missing value makes the whole calculation NULL.

See it in code

Walk through the code

sql
1SELECT2  product_name,3  unit_price,4  quantity,5  unit_price * quantity                   AS line_total,6  unit_price * quantity * 0.10            AS discount,7  ROUND(unit_price * quantity * 0.90, 2)  AS payable,8  quantity / 2.0                          AS half_boxes9FROM order_items;

1/4Raw columns straight from the table.

Each new column is computed per row and appears only in the output. ROUND(numeric, 2) works in PostgreSQL and MySQL.

Save yourself the pain

Common mistakes

Oops

Writing quantity / 2 and getting 1 instead of 1.5 in PostgreSQL.

Do this instead

Divide by 2.0, or cast one side: quantity::numeric / 2.

Oops

price * quantity + tax when you meant price * (quantity + tax).

Do this instead

Add brackets for anything beyond a single operation. They cost nothing and remove doubt.

Your mission

Build a bill

~20 min

Quick check

In PostgreSQL, what does SELECT 9 / 4; return?

Go deeper

  1. 1Calculate line totals and a discounted price for each order item.
  2. 2Check what happens when you divide two integers in your database (PostgreSQL and SQL Server drop the decimal part, MySQL does not).
  3. 3Give every calculated column a clear alias.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge