How Div() Works in PostgreSQL

In PostgreSQL, the div() function returns the integer quotient of its first argument divided by its second argument.

Syntax

The official syntax goes like this:

div(y numeric, x numeric)

Example

Here’s an example of how it works.

SELECT div(12, 3);

Result:

4

In this case I divided 12 by 3, and the result is 4.

More Divisions

Here’s a few more divisions on the same number.

SELECT 
  div(12, 1),
  div(12, 2),
  div(12, 3),
  div(12, 4);

Result:

 div | div | div | div
-----+-----+-----+-----
  12 |   6 |   4 |   3

Fractional Results

This function returns the integer quotient, so any fractional amounts are omitted from the result.

SELECT div(12, 5);

Result:

2

12 divided 5 is actually 2.4, but this function doesn’t return the fractional part and so we get 2.

There doesn’t appear to be any rounding done either. For example, 9 divided by 5 is 1.8, but div() returns 1 (it doesn’t round up to 2).

SELECT div(9, 5);

Result:

1

So it behaves more like applying trunc() (or perhaps even floor()) to the result, rather than round() or ceiling().

Division by Zero

If you try to divide a number by zero, you’ll get an error.

SELECT div(12, 0);

Result:

ERROR: division by zero

But if you divide zero by another number, then you’ll just get zero.

SELECT div(0, 12);

Result:

0