Arithmetic and Operators
Add, subtract, multiply and divide in SQL.
Doing Math in SELECT
SQL is not just for fetching rows. You can compute values right inside a query using arithmetic operators.
In this lesson you will add, subtract, multiply and divide using columns and literals, give the results names, and understand how PostgreSQL decides the type of each result.
Imagine an order_items table with quantity and unit_price. We can compute a line total without touching application code.
SELECT quantity, unit_price, quantity * unit_price AS line_total
FROM order_items;The Five Arithmetic Operators
PostgreSQL supports the usual operators:
+addition-subtraction*multiplication/division%modulo (remainder)
They work on numeric columns and literals just like in any programming language. The query below shows each one in action.
SELECT
10 + 3 AS sum,
10 - 3 AS difference,
10 * 3 AS product,
10 / 3 AS quotient,
10 % 3 AS remainder;All lessons in this course
- Arithmetic and Operators
- Rounding and Truncating
- Integer vs Decimal Division
- Useful Math Functions