Mathematical Operators
Part of the Fundamentals section of Coddy's SQL journey — lesson 23 of 72.
In SQL, you can perform calculations directly with column values in your queries. This is useful when you need to compute new values based on existing data. For example:
| Operator | Operation |
|---|---|
| + | Addition |
| - | Subtraction |
| Multiplication | |
| / | Division |
SELECT price + 10 as increased_price,
price - 10 as reduced_price,
price 10 as multiple_price,
price / 2 as half_price
FROM products;Important note about division: When dividing integers in SQL, the result depends on the data types involved:
- Integer ÷ Integer = Integer (truncated):
7 / 2 = 3(not 3.5)
- Integer ÷ Float = Float:
7 / 2.0 = 3.5
- Float ÷ Integer = Float:
7.0 / 2 = 3.5
To get decimal results when dividing integers, make sure at least one operand is a float (use values like 2.0 instead of 2).
Challenge
EasyAvailable tables and columns:
<strong>products</strong>:<strong>id</strong>,<strong>price</strong>,<strong>quantity</strong>
Create two calculated columns:
- First column named
high_mix_op:- Take the price column
- Multiply it by 2
- Subtract 20 from the result
- Second column named
low_mix:- Take the quantity column
- Divide it by 1.5
- Add 5 to the result
Cheat sheet
SQL supports arithmetic operations directly with column values using these operators:
| Operator | Operation |
|---|---|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
You can perform calculations and assign aliases to the results:
SELECT price + 10 as increased_price,
price - 10 as reduced_price,
price * 10 as multiple_price,
price / 2 as half_price
FROM products;Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4More Keywords
The IN keywordThe BETWEEN keywordThe LIKE keywordThe AS keywordRecap - Cellphone Models2Conditions
Conditions BasicsThe AND keywordThe OR keywordThe NOT keywordMultiple Conditions CombinedParenthesisBooleans5Arithmetic Operations
Mathematical OperatorsMathematical ColumnsThe Modulo OperationThe ROUND() Function3Specific Return Format
Null valuesSort Results Part 1Sort Results Part 2Recap - Cyber Security FirmLimit number of recordsRecap - Vehicle Factory6Intro Challenges
Recap - Parliamentary ElectionRecap - Police Criminal ArrestRecap - Bar Beverage ContainerRecap - Engineer new columns