The PostgreSQL DIV()
function is used to perform integer division. This function is essential for dividing one number by another and returning the integer part of the quotient, discarding any fractional part.
number1 / number2
The DIV()
function has the following components:
number1
: The dividend.number2
: The divisor.Let's look at some examples of PostgreSQL DIV()
function queries:
SELECT 10 / 3 AS result;
This query returns the result of the integer division of 10 by 3, which is 3.
SELECT dividend, divisor, dividend / divisor AS result
FROM division_data;
This query retrieves the dividend
, divisor
, and the result of their integer division from the division_data
table.
SELECT dividend, divisor, dividend / divisor AS result
FROM division_data
WHERE dividend < 0;
This query retrieves the dividend
, divisor
, and the result of their integer division from the division_data
table where the dividend
is negative.
Let's go through a complete example that includes creating a table, inserting data, and using the DIV() function to perform integer division.
This step involves creating a new table named division_data
to store numerical data for division.
CREATE TABLE division_data (
id SERIAL PRIMARY KEY,
dividend NUMERIC,
divisor NUMERIC
);
In this example, we create a table named division_data
with columns for id
, dividend
, and divisor
.
This step involves inserting some sample data into the division_data
table.
INSERT INTO division_data (dividend, divisor)
VALUES (10, 3),
(20, 4),
(-30, 5),
(40, 6);
Here, we insert data into the division_data
table.
This step involves using the DIV()
function to perform integer division on the data in the division_data
table.
Basic DIV()
SELECT dividend, divisor, dividend / divisor AS result
FROM division_data;
This query performs division on each pair of values in the 'dividend' and 'divisor' columns of the 'division_data' table.
DIV() with Negative Values
SELECT dividend, divisor, dividend / divisor AS result
FROM division_data
WHERE dividend < 0;
This query performs division on each pair of values in the 'dividend' and 'divisor' columns of the 'division_data' table where the 'dividend' is less than 0.
These queries demonstrate how to use the DIV()
function to perform integer division on the data in the division_data
table, including basic usage and handling negative values.
The PostgreSQL DIV()
function is a fundamental tool for performing integer division and obtaining the integer part of the quotient. Understanding how to use the DIV()
function and its syntax is essential for effective data retrieval and manipulation in PostgreSQL databases.