SQL Expressions and Arithmetic
What you will learn
- How to calculate with
+,-,*,/and%in theSELECTlist - The order of operations and how brackets change it
- Why integer division drops the decimals, and how to avoid it
- How to build a calculated column from real columns
This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.
1. An expression is a calculation
Anything that produces a value is an expression: a column, a constant, or a calculation made from them. The SELECT list can hold expressions, and the database calculates one value per row. You can try them without a table:
SELECT 7 + 3 AS plus, 7 - 3 AS minus, 7 * 3 AS times, 7 % 3 AS remainder;
plus minus times remainder
---- ----- ----- ---------
10 4 21 1
(1 row)
SELECT 7 + 3 AS plus, 7 - 3 AS minus, 7 * 3 AS times, 7 % 3 AS remainder;
plus minus times remainder
---- ----- ----- ---------
10 4 21 1
(1 row)
SELECT 7 + 3 AS plus, 7 - 3 AS minus, 7 * 3 AS times, 7 % 3 AS remainder;
plus minus times remainder
---- ----- ----- ---------
10 4 21 1
(1 row)
% gives the remainder after division: 7 divided by 3 is 2 with 1 left over.
2. Order of operations
Multiplication and division are done before addition and subtraction, as in school. Brackets change the order:
SELECT 2 + 3 * 4 AS without_brackets, (2 + 3) * 4 AS with_brackets;
without_brackets with_brackets
---------------- -------------
14 20
(1 row)
SELECT 2 + 3 * 4 AS without_brackets, (2 + 3) * 4 AS with_brackets;
without_brackets with_brackets
---------------- -------------
14 20
(1 row)
SELECT 2 + 3 * 4 AS without_brackets, (2 + 3) * 4 AS with_brackets;
without_brackets with_brackets
---------------- -------------
14 20
(1 row)
When in doubt, add brackets. They cost nothing and make the meaning clear to the next reader.
3. Integer division
Here is a trap that catches many beginners. When both numbers are whole numbers, SQLite divides and drops the decimals:
SELECT 7 / 2 AS whole_numbers, 7 / 2.0 AS with_a_decimal, 7.0 / 2 AS other_way;
whole_numbers with_a_decimal other_way
------------- -------------- ---------
3 3.5 3.5
(1 row)
SELECT 7 / 2 AS whole_numbers, 7 / 2.0 AS with_a_decimal, 7.0 / 2 AS other_way;
whole_numbers with_a_decimal other_way
------------- -------------- ---------
3 3.5 3.5
(1 row)
SELECT 7 / 2 AS whole_numbers, 7 / 2.0 AS with_a_decimal, 7.0 / 2 AS other_way;
whole_numbers with_a_decimal other_way
------------- -------------- ---------
3 3.5 3.5
(1 row)
7 / 2 gives 3, not 3.5. If either number has a decimal point, the result keeps its decimals. To be safe, write one of the numbers with a decimal point, as in 7 / 2.0.
In other databases. PostgreSQL behaves like SQLite: its documentation says division of integer types truncates toward zero (
5 / 2gives2). MySQL is different: its/returns a decimal even for whole numbers (its documentation shows3/5giving0.60) and it has a separateDIVoperator for whole-number division. This is taken from the official documentation and was not run here. The difference is a good reason to write7 / 2.0when you mean decimals.
4. Calculated columns from real data
Now use real columns. The result has one calculated value per row:
Each product has a selling price and a cost. The margin is the difference:
SELECT name, price, cost, price - cost AS margin FROM products ORDER BY product_id LIMIT 5;
name price cost margin
---------------- ----- ----- ------------------
Steel pan 6.6 3.96 2.6399999999999997
Ceramic mug 44.1 30.21 13.89
Wooden spoon set 29.5 13.3 16.2
Glass jar 5.4 2.45 2.95
Chopping board 26.4 14.63 11.769999999999998
(5 rows)
Look at the first margin: 2.6399999999999997, not 2.64. Computers store decimal numbers (REAL) in binary, and some decimals cannot be stored exactly, so a calculation can end with a tiny error. Lesson 1.6 shows how to round it away.
The value of the stock on the shelf is the cost times the number in stock:
SELECT name, stock, cost, stock * cost AS stock_value FROM products ORDER BY product_id LIMIT 5;
name stock cost stock_value
---------------- ----- ----- -----------
Steel pan 0 3.96 0.0
Ceramic mug 150 30.21 4531.5
Wooden spoon set 0 13.3 0.0
Glass jar 40 2.45 98.0
Chopping board 80 14.63 1170.4
(5 rows)
The bank keeps money in whole cents (192400 means 1,924.00). Dividing by 100 converts to units, but with whole numbers the cents are lost:
SELECT account_id, balance_cents, balance_cents / 100 AS whole_units, balance_cents / 100.0 AS units
FROM accounts ORDER BY account_id LIMIT 5;
account_id balance_cents whole_units units
---------- ------------- ----------- ------
1 192400 1924 1924.0
2 52078 520 520.78
3 62780 627 627.8
4 99900 999 999.0
5 153100 1531 1531.0
(5 rows)
A made-up yearly charge of 2% of the balance, still in cents:
SELECT account_id, balance_cents, balance_cents * 2 / 100 AS two_percent FROM accounts ORDER BY account_id LIMIT 5;
account_id balance_cents two_percent
---------- ------------- -----------
1 192400 3848
2 52078 1041
3 62780 1255
4 99900 1998
5 153100 3062
(5 rows)
Each assignment has max_points. A made-up pass mark of 40% of the points:
SELECT title, max_points, max_points * 0.4 AS pass_mark FROM assignments ORDER BY assignment_id LIMIT 5;
title max_points pass_mark
---------- ---------- ---------
Midterm 100 40.0
Project 100 40.0
Quiz 1 20 8.0
Homework 2 50 20.0
Homework 1 10 4.0
(5 rows)
A course has credits. Suppose each credit means 15 hours of study (made up):
SELECT code, title, credits, credits * 15 AS study_hours FROM courses ORDER BY course_id LIMIT 5;
code title credits study_hours
------- ---------------------- ------- -----------
MATH101 Foundations of Algebra 4 60
MATH201 Geometry 3 45
MATH301 Statistics 4 60
SCI101 General Science 4 60
SCI201 Chemistry 4 60
(5 rows)
The stored table does not change. The calculation exists only in the result.
5. Calculating with NULL
If any value in an expression is NULL (no value), the whole result is NULL. SQL cannot calculate with something that is missing:
SELECT 5 + NULL AS result, NULL * 10 AS also_null;
result also_null
------ ---------
NULL NULL
(1 row)
SELECT 5 + NULL AS result, NULL * 10 AS also_null;
result also_null
------ ---------
NULL NULL
(1 row)
SELECT 5 + NULL AS result, NULL * 10 AS also_null;
result also_null
------ ---------
NULL NULL
(1 row)
Chapter 2 shows how to test for NULL and how to replace it with a default value.
Worked example: from cents to a readable amount
A column stores 192400 and the report must show 1924.00.
| Step | Expression | Result |
|---|---|---|
| Divide by 100 with whole numbers | 192400 / 100 |
1924 (fine here, but cents are lost when there are any) |
| Divide by 100 with a decimal | 192400 / 100.0 |
1924.0 |
| Round to two places (lesson 1.6) | ROUND(192400 / 100.0, 2) |
1924.0 |
Always divide by 100.0, not 100, so a balance of 192450 becomes 1924.5 and not 1924. The amounts are made up.
Common mistakes
- Dividing whole numbers and expecting decimals.
7 / 2is3. Write7 / 2.0. - Forgetting brackets.
2 + 3 * 4is 14, not 20. - Expecting a calculation with
NULLto give a number. It givesNULL. - Thinking the table changed. A calculated column exists only in the result.
Key takeaways
- The
SELECTlist can hold calculations; the database computes one value per row. *and/come before+and-; brackets change the order.- Whole number divided by whole number drops the decimals in SQLite; use a decimal such as
100.0. - Anything calculated with
NULLisNULL. - Calculated columns never change the stored data.
Practice
1. What does SELECT 10 - 2 * 3; return?
Show answer
4. The multiplication is done first (2 * 3 = 6), then 10 - 6.
2. What does SELECT 9 / 4; return in SQLite, and how do you get 2.25?
Show answer
2, because both numbers are whole. Write 9 / 4.0 (or 9.0 / 4) to get 2.25.
3. What does 17 % 5 return?
Show answer
2: 17 divided by 5 is 3 with a remainder of 2.
4. What does SELECT 100 + NULL; return?
Show answer
NULL. A calculation with a missing value gives a missing value.
5. A table has price and quantity. Write the column that gives the total for each row.
Show answer
SELECT price * quantity AS total FROM ... (with the real table name).
6. Does SELECT price * 2 AS double_price FROM products change the prices in the table?
Show answer
No. A query only reads. The doubled price exists only in the result.