MySQL Tutorial
MySQL Installation and Configuration
MySQL Database Operations
Database Design
MySQL Data Types
MySQL Storage Engines
MySQL Basic Operations of Tables
MySQL Constraints
MySQL Operators
MySQL Function
MySQL Manipulate Table Data
MySQL View
MySQL Indexes
MySQL Stored Procedure
MySQL Trigger
MySQL Transactions
MySQL Character Set
MySQL User Management
MySQL Database Backup and Recovery
MySQL Log
MySQL Performance Optimization
MySQL supports a number of arithmetic operators that you can use in your SQL statements. Here are the basic ones:
Addition (+
): Adds two numbers.
Example: SELECT 5 + 3;
//Returns 8
Subtraction (-
): Subtracts the second number from the first.
Example: SELECT 5 - 3;
//Returns 2
Multiplication (*
): Multiplies two numbers.
Example: SELECT 5 * 3;
//Returns 15
Division (/
): Divides the first number by the second. If the division is not exact, the result is a decimal.
Example: SELECT 10 / 3;
//Returns 3.3333
Modulo (%
or MOD
): Returns the remainder of a division operation.
Example: SELECT 10 % 3;
//Returns 1
Or: SELECT MOD(10,3);
//Returns 1
Arithmetic Operators in a Table:
You can also use these operators in your queries on a table. For example, consider the following products
table:
ProductID | Price | Quantity |
---|---|---|
1 | 10 | 5 |
2 | 20 | 3 |
3 | 15 | 7 |
If you want to calculate the total cost for each product, you can multiply the Price
and Quantity
columns:
SELECT ProductID, Price, Quantity, Price * Quantity AS TotalCost FROM products;
This will return:
ProductID | Price | Quantity | TotalCost |
---|---|---|---|
1 | 10 | 5 | 50 |
2 | 20 | 3 | 60 |
3 | 15 | 7 | 105 |
The AS
keyword is used to rename the calculated column to TotalCost
.
NOTE: Be careful when performing division operations, as MySQL performs integer division when both operands are integers. For example, SELECT 5 / 2;
will return 2
instead of 2.5
. To get a decimal result, make sure at least one of the operands is a decimal, like SELECT 5 / 2.0;
.
MySQL arithmetic operators examples:
SELECT 5 + 3 AS addition, 5 - 3 AS subtraction, 5 * 3 AS multiplication, 5 / 3 AS division, 5 % 3 AS modulus;
How to use addition operator in MySQL:
SELECT column1 + column2 AS sum FROM table_name;
Subtraction operator in MySQL queries:
SELECT column1 - column2 AS difference FROM table_name;
Multiplication operator usage in MySQL:
SELECT column1 * column2 AS product FROM table_name;
Division operator in MySQL arithmetic:
SELECT column1 / column2 AS quotient FROM table_name;
Modulus operator in MySQL calculations:
SELECT column1 % column2 AS remainder FROM table_name;
Order of operations in MySQL arithmetic expressions:
SELECT (column1 + column2) * column3 AS result FROM table_name;
Performing calculations with MySQL arithmetic operators:
SELECT (column1 * 2) + (column2 / 3) AS result FROM table_name;
Using parentheses in MySQL arithmetic:
SELECT (column1 + column2) * column3 AS result FROM table_name;