SQL integer division
Divides two integers and drops the fraction toward zero: 7 / 2 is 3 and -7 / 2 is -3 on SQL Server, PostgreSQL and SQLite. MySQL and Oracle need DIV or TRUNC.
- Kategorie
- Math
- Returns
integer- In this category
- 49 of 82
Syntax
7 / 2
7 DIV 2 -- MySQL
div(7, 2) -- PostgreSQL
TRUNC(7 / 2) -- Oracle
Each block is a separate form. The support table and the examples show which engine takes which.
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Ja | / on integers truncates toward zero |
| PostgreSQL | Ja | int / int truncates; div(numeric, numeric) is the explicit integer-division function |
| MySQL | Ja | DIV is a keyword: 7 DIV 2 is 3; the plain / always returns a decimal on MySQL |
| SQLite | Ja | int / int truncates toward zero |
| Oracle | Different name or syntax | / never truncates: 7 / 2 is 3.5. Use TRUNC(7 / 2) for integer division |
Beispiele
SQL Server
SELECT 7 / 2 AS int_div, -7 / 2 AS toward_zero; -- 3, -3
Oracle
SELECT 7 / 2 AS plain, TRUNC(7 / 2) AS int_div FROM dual; -- 3.5, 3
MySQL
SELECT 7 DIV 2 AS three, 7 / 2 AS decimal_result; -- 3, 3.5000
PostgreSQL
SELECT total_rows / page_size AS full_pages, div(total_rows, page_size) AS same FROM jobs;
Gut zu wissen
- The fix for 1/2 = 0 on SQL Server, PostgreSQL and SQLite is decimal promotion: 1.0 / 2, CAST(x AS DECIMAL), or multiply by 1.0 before dividing.
- Truncation is toward zero: -7 / 2 is -3, which differs from FLOOR(-3.5) = -4. Do not swap FLOOR for integer division on negatives.
- MySQL and Oracle never truncate on /: 7 / 2 is 3.5000 on MySQL and 3.5 on Oracle. Code ported from SQL Server that relies on truncation silently changes results there; use DIV (MySQL) or TRUNC (Oracle).
- Division by zero stays an error or NULL per engine; integer division does not change that.
Questions about DIV
Why is 1/2 equal to 0 in my query?
Integer division: on SQL Server, PostgreSQL and SQLite, two integer operands give an integer result with the fraction dropped. Write 1.0 / 2 or CAST one operand to a decimal type to get 0.5. MySQL and Oracle already return 0.5.
Does -7 / 2 round or truncate?
It truncates toward zero: -3 on SQL Server, PostgreSQL and SQLite, and with MySQL's -7 DIV 2. That is not the same as FLOOR(-3.5), which is -4, a common off-by-one on negatives.
What is MySQL's DIV operator?
The explicit integer-division keyword: 7 DIV 2 is 3. It exists because MySQL's plain / always returns a decimal and never truncates.
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.