postgresql common functions
Introduction
Function ( function ) is some predefined code modules that can calculate and process the input, and finally output a
result value. PostgreSQL functions can be divided into two categories: scalar function ( scalar function ) and aggregation function ( aggregation
function ). Scalar functions return a result for each input, and aggregate functions summarize a result for a set of inputs.
Common
system functions fall into the following
categories: mathematical functions, character functions, datetime functions, and type conversion functions
. In addition to using these built-in
functions, PostgreSQL also supports creating custom functions ( UDF )
math function
arithmetic operator
PostgreSQL supports the following arithmetic operators:
absolute value
-- abs(x)函数用于计算 x 的绝对值
select abs(-17.4);
rounding function
ceil(dp)/ceiling(dp)
function to calculate dp
the smallest integer greater than or equal to ; floor(dp)
function to calculate the largest integer less than or
equal to dp
; round(dp)
function to round to an integer; trunc(dp)
function to round toward zero
select ceil(-42.8), floor(-42.8), round(12.45), trunc(12.8);
Also, round(dp, s)
the function rounds to s decimal places; trunc(dp, s)
the function truncates to s
s decimal places.
square root
power(a, b)
Function Compute a
to b
the power; sqrt(dp)
Function Compute dp
square root; cbrt(dp)
Function Compute dp
cube root
Exponential and logarithmic
exp(dp)
The function calculates the exponent with the natural constant e
as the base, the ln(dp) function calculates the logarithm with the natural constant e
as the base,
log(dp)/log10(dp)
the function calculates the logarithm 10
with the base as the logarithm, and log(b, x)
the function calculates the logarithm with the base b
as the logarithm.
integer quotient and remainder
div(y, x)
The function calculates the integer quotient y
divided by , and the function calculates the remainder when divided by .x
mod(y, x)
y
x
Radians and Angles
degrees(dp)
The function is used to convert radians to degrees, and radians(dp)
the function is used to convert angles to radians.
constant π
select pi();
symbolic function
select sign(-9.7);
The sign(dp) function returns the sign of the argument, and the possible results are -1, 0, +1.
Generate random numbers
PostgreSQL provides a function random() that returns a random number.
random() returns a random number greater than or equal to 0 and less than 1, and the type is a double-precision floating-point number.
select random();
setseed(dp)
The function can set the seed number for the subsequent random() function, range: -1.0 <= dp <= 1.0
.
select setseed(0);
select random();
The same seed yields the same random number for reproducible results.