SQL arithmetic operators
Adds, subtracts, multiplies and divides. A NULL operand makes the result NULL, and 7 / 2 is 3 on SQL Server, PostgreSQL and SQLite but 3.5 on MySQL and Oracle.
- Categoría
- Math
- Returns
depends on operand types- In this category
- 47 of 82
Sintaxis
a + b
a - b
a * b
a / b
Each block is a separate form. The support table and the examples show which engine takes which.
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sí | Supported under this name. |
| PostgreSQL | Sí | Supported under this name. |
| MySQL | Sí | Supported under this name. |
| SQLite | Sí | Supported under this name. |
| Oracle | Sí | Supported under this name. |
Ejemplos
PostgreSQL
SELECT 7 + 2 AS nine, 7 / 2 AS truncated, 7 / 2.0 AS exact; -- 9, 3, 3.5000000000000000
MySQL
SELECT 7 / 2 AS not_truncated, 7 DIV 2 AS truncated; -- 3.5000, 3
Any engine
SELECT 5 + NULL AS null_result; -- NULL
SQL Server
DECLARE @discount decimal(4, 2) = 0.10; SELECT price * quantity * (1 - @discount) AS net FROM order_items;
Conviene saberlo
- Any NULL operand makes the whole expression NULL: 5 + NULL is NULL, not 5. Wrap with COALESCE when zero is the intent.
- Integer / integer truncates on SQL Server, PostgreSQL and SQLite: 7 / 2 is 3. MySQL returns 3.5000 and Oracle 3.5. Multiply one side by 1.0 to get the fraction everywhere.
- Type promotion decides the result type: int + decimal is decimal, decimal + float is float, so the same expression can be exact on one column and lossy on another.
Questions about + - * /
What does 5 + NULL return in SQL?
NULL. Arithmetic with any NULL operand yields NULL on every engine: the value is unknown, so the sum is unknown. Use COALESCE(x, 0) when a zero default is what you mean.
Why does 7 / 2 give 3?
On SQL Server, PostgreSQL and SQLite, two integer operands mean integer division, which truncates. 7 / 2.0, or CASTing one side, produces 3.5. MySQL and Oracle already return 3.5 for 7 / 2.
Do operators overflow the same way everywhere?
No. SQL Server and PostgreSQL raise an error when INT arithmetic passes 2147483647. MySQL computes integer expressions in 64 bits and errors only past BIGINT. SQLite promotes to float past the 64-bit range. Oracle NUMBER errors only past about 1e126.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.