SQL division uses the / operator. When the divisor is an integer, the integer is returned and the decimal is discarded. When the divisor is a decimal, the floating point is returned and the decimal place is retained. Dividing by 0 will report an error, and the result will be negative if the sign is different. You can use the ROUND() function to preserve a specified number of decimal places, and convert the number to floating point to avoid loss of precision.
Division in SQL
How to perform division?
Use /
operators for division in SQL.
When the divisor is an integer
If the divisor is an integer, SQL will return an integer result and the decimal part will be discarded. For example:
<code class="sql">SELECT 10 / 3; -- 返回 3</code>
When the divisor is a decimal
If the divisor is a decimal, SQL will return a floating point result with decimal places retained. For example:
<code class="sql">SELECT 10 / 3.5; -- 返回 2.857142857142857</code>
Special cases
Use the ROUND() function
To retain a specific number of decimal places, you can use the ROUND()
function. For example:
<code class="sql">SELECT ROUND(10 / 3.5, 2); -- 返回 2.86</code>
Avoid loss of precision
To avoid loss of precision, it is recommended to convert the number to floating point before performing division. For example:
<code class="sql">SELECT CAST(10 AS FLOAT) / CAST(3.5 AS FLOAT); -- 返回 2.857142857142857</code>
The above is the detailed content of How to write division in sql. For more information, please follow other related articles on the PHP Chinese website!