// math reference

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.

Catégorie
Math
Returns
depends on operand types
In this category
47 of 82

Syntaxe

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.

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Oui Supported under this name.
PostgreSQL Oui Supported under this name.
MySQL Oui Supported under this name.
SQLite Oui Supported under this name.
Oracle Oui Supported under this name.

Exemples

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;

Bon à savoir

  • 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.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.