PostgreSQL DIV() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL DIV()
function to perform integer division.
Introduction to the PostgreSQL DIV() function
The DIV()
function is a useful tool for performing integer division. Unlike the division operator (/
), which returns a floating-point result, the DIV()
function provides an integer quotient.
Here’s the basic syntax of the DIV()
function:
In this syntax:
dividend
is the number that you want to divide.divisor
is the number to which to divide the dividend.
The DIV()
function returns the integer quotient of the division.
PostgreSQL DIV() function examples
Let’s explore some examples of using the DIV()
function.
1) Basic DIV() function example
The following uses the DIV()
function to return the result of dividing 10 by 3:
Output:
The result is 3.
Unlike regular division, the DIV()
function truncates any fractional part of the result and returns only the integer part.
2) Grouping data into bins
You can group numerical data data into bins using the DIV()
function. For example, you can group film from the film
table of the sample database into bins of 30 minutes:
Output:
In this example, we group the lengths of films into bins of 30 minutes.
3) Using the PostgreSQL DIV() for calculating ages
First, create a new table called employees
and insert some data into it:
Output:
Second, calculate the age of each employee:
Output:
How it works.
- Use the AGE() function to calculate age.
- Use the EXTRACT() function to extract the year from the age.
- Use the
DIV()
function to return the integer part of the age.
Summary
- Use the PostgreSQL
DIV()
function to perform integer division.