The DIV function in MySQL is used to perform integer division, which means it divides two numbers and returns the quotient as an integer (ignoring any remainder). It’s particularly useful when you need to perform division but only care about the whole number part of the result.
Syntax:
SELECT dividend DIV divisor;
dividend: The numerator (the number being divided).divisor: The denominator (the number dividing the dividend).
Behavior:
- The result of
DIVwill always be an integer (integer division). - The remainder from the division is discarded (it is not included in the result).
Example Usage:
-- Example 1: Integer Division with Positive Numbers
SELECT 10 DIV 3;
-- Result: 3 (10 divided by 3 is 3 with a remainder of 1)
-- Example 2: Integer Division with Negative Numbers
SELECT -10 DIV 3;
-- Result: -4 (-10 divided by 3 is -3 with a remainder of -1, so the result is truncated)
-- Example 3: Integer Division Resulting in Zero
SELECT 5 DIV 10;
-- Result: 0 (5 divided by 10 results in a fraction, but the result is truncated to 0)
Important Notes:
- The
DIVfunction truncates the result to an integer, so it doesn't round; it simply discards any fractional part. - If you want to round the result instead of truncating it, you would need to use other functions like
ROUND(). DIVwill still work for negative numbers but the result is truncated toward zero, meaning it rounds the quotient towards zero instead of flooring it (which is how regular division might behave).
Comparison with Regular Division:
Regular division (/) in MySQL can return a floating-point result, while DIV returns an integer result.
SELECT 10 / 3; -- Result: 3.3333
SELECT 10 DIV 3; -- Result: 3
In summary, DIV is a useful function in MySQL when you want to perform division but only need the integer part of the quotient.
No comments:
Post a Comment