PostgreSQL 常用函数
系统梳理 PostgreSQL 聚合函数、21 项数学函数、8 项三角函数、32 项字符串函数/操作符及 9 项格式化类型转换函数,并在离线 SQLite 3.53.1(内置数学引擎)中完成核心算例实测。
学完这一章,你能够
- 系统梳理 PostgreSQL 聚合函数、21 项数学函数、8 项三角函数、32 项字符串函数/操作符及 9 项格式化类型转换函数,并在离线 SQLite 3.53.1(内置数学引擎)中完成核心算例实测。
内置函数分类与常用聚合函数
PostgreSQL 提供了丰富的内置函数,既包含面向分组统计的聚合函数,也包含面向单行表达式处理的数值、字符串、日期时间与类型转换标量函数。日常高频函数家族涵盖:`COUNT`(统计行数)、`MAX`(取最大值)、`MIN`(取最小值)、`AVG`(求平均值)、`SUM`(求和)、`ARRAY_AGG`/数组聚合(将包含 `NULL` 在内的多行值聚合成数组),以及完备的数值(Numeric)函数族与字符串(String)函数族。本站离线 SQLite 实测在 7 行 `COMPANY` 表上验证了 `COUNT=7`、`MAX=85000`、`MIN=10000`、`AVG=37142.86`、`SUM=260000` 及有序数组聚合。
数学函数与三角函数
PostgreSQL 数学函数常针对 `double precision`、`numeric` 等不同数值类型提供重载版本;除特别注明外,返回值类型与输入参数类型保持一致。下两张参考表完整收录 21 项基础数学函数(绝对值、立方根、取整、对数、幂、圆整、截断与随机数等)与 8 项三角/反三角函数(`acos`、`asin`、`atan`、`atan2`、`cos`、`cot`、`sin`、`tan`)。本站实验利用已启用 `ENABLE_MATH_FUNCTIONS` 的 SQLite 3.53.1 与标准数学库核对了核心数值与三角函数算例。
字符串函数、操作符与类型转换函数
字符串处理函数与 `||` 连接操作符覆盖字符/字节/位长度统计、大小写转换、子串定位与切片、正则匹配抽取、两端裁剪、填充、重复、替换、字符映射、十六进制与 MD5 散列等 32 项能力(需注意 `strpos()` 的实际返回类型为整型 `integer`)。在数据格式互转方面,PostgreSQL 提供 `to_char`、`to_date`、`to_number` 与 `to_timestamp` 四个模板驱动的转换函数,支持将时间戳、间隔或数值按格式掩码转为文本,或将文本/UNIX 纪元秒解析回日期、数值与时间戳。本站离线实验实测了 `||`、`lower`、`upper`、`length`、`octet_length`、`substr`、`trim`/`ltrim`/`rtrim`、`replace`、`instr`、`md5` 及 UNIX 纪元 `1284352323 -> 2010-09-13 04:32:03 UTC` 转换。
PostgreSQL 常用数学函数一览
| 函数 | 返回类型 | 描述 | 示例 | 结果 |
|---|---|---|---|---|
| abs(x) | 同参数类型 | 绝对值 | abs(-17.4) | 17.4 |
| cbrt(double) | double precision | 立方根 | cbrt(27.0) | 3 |
| ceil(double/numeric) | 同参数类型 | 不小于参数的最小整数(向上取整) | ceil(-42.8) | -42 |
| degrees(double) | double precision | 将弧度转换为角度 | degrees(0.5) | 28.6478897565412 |
| exp(double/numeric) | 同参数类型 | 自然指数 e^x | exp(1.0) | 2.71828182845905 |
| floor(double/numeric) | 同参数类型 | 不大于参数的最大整数(向下取整) | floor(-42.8) | -43 |
| ln(double/numeric) | 同参数类型 | 自然对数 | ln(2.0) | 0.693147180559945 |
| log(double/numeric) | 同参数类型 | 以 10 为底的对数 | log(100.0) | 2 |
| log(b numeric, x numeric) | numeric | 以 b 为底 x 的对数 | log(2.0, 64.0) | 6.0000000000 |
| mod(y, x) | 同参数类型 | y 除以 x 的余数 | mod(9, 4) | 1 |
| pi() | double precision | 圆周率 π 常量 | pi() | 3.14159265358979 |
| power(a double, b double) | double precision | 计算 a 的 b 次幂(双精度) | power(9.0, 3.0) | 729 |
| power(a numeric, b numeric) | numeric | 计算 a 的 b 次幂(高精度数值) | power(9.0, 3.0) | 729 |
| radians(double) | double precision | 将角度转换为弧度 | radians(45.0) | 0.785398163397448 |
| random() | double precision | 生成 [0.0, 1.0) 区间的伪随机数 | random() | 随机浮点值 |
| round(double/numeric) | 同参数类型 | 四舍五入为最接近整数 | round(42.4) | 42 |
| round(v numeric, s int) | numeric | 四舍五入保留 s 位小数 | round(42.438, 2) | 42.44 |
| sign(double/numeric) | 同参数类型 | 返回参数符号(-1、0 或 +1) | sign(-8.4) | -1 |
| sqrt(double/numeric) | 同参数类型 | 平方根 | sqrt(2.0) | 1.4142135623731 |
| trunc(double/numeric) | 同参数类型 | 向零截断为整数 | trunc(42.8) | 42 |
| trunc(v numeric, s int) | numeric | 截断至 s 位小数 | trunc(42.438, 2) | 42.43 |
PostgreSQL 三角函数列表
| 函数 | 描述 |
|---|---|
| acos(x) | 反余弦 |
| asin(x) | 反正弦 |
| atan(x) | 反正切 |
| atan2(x, y) | y/x 的反正切(PostgreSQL 参数顺序为 atan2(y, x)) |
| cos(x) | 余弦 |
| cot(x) | 余切 |
| sin(x) | 正弦 |
| tan(x) | 正切 |
PostgreSQL 字符串函数与操作符一览
| 函数/操作符 | 返回类型 | 描述 | 示例 | 结果 |
|---|---|---|---|---|
| string || string | text | 字符串连接操作符 | 'Post' || 'greSQL' | PostgreSQL |
| bit_length(string) | int | 返回字符串的二进制位数 | bit_length('jose') | 32 |
| char_length(string) | int | 返回字符串中的字符数 | char_length('jose') | 4 |
| convert(string USING conversion_name) | text | 按指定编码转换名称转换字符编码(历史语法,新版对应 convert_to/convert_from) | convert('PostgreSQL' using iso_8859_1_to_utf8) | 'PostgreSQL' |
| lower(string) | text | 将字符串转为小写 | lower('TOM') | tom |
| octet_length(string) | int | 返回字符串占用的字节数 | octet_length('jose') | 4 |
| overlay(string PLACING replacement FROM int [FOR int]) | text | 从指定位置替换子串 | overlay('Txxxxas' placing 'hom' from 2 for 4) | Thomas |
| position(substring IN string) | int | 返回子串首次出现的 1-based 位置 | position('om' in 'Thomas') | 3 |
| substring(string [FROM int] [FOR int]) | text | 按起始位置和长度截取子串 | substring('Thomas' from 2 for 3) | hom |
| substring(string FROM pattern) | text | 提取匹配 POSIX 正则表达式的子串 | substring('Thomas' from '...$') | mas |
| substring(string FROM pattern FOR escape) | text | 提取匹配 SQL 正则模式的子串 | substring('Thomas' from '%#"o_a#"_' for '#') | oma |
| trim([LEADING | TRAILING | BOTH] [chars] FROM string) | text | 从开头/结尾/两端移除指定字符集(默认空格) | trim(both 'x' from 'xTomxx') | Tom |
| upper(string) | text | 将字符串转为大写 | upper('tom') | TOM |
| ascii(text) | int | 返回首字符的 ASCII / Unicode 码点 | ascii('x') | 120 |
| btrim(string [, characters]) | text | 移除字符串首尾包含于 characters 的字符 | btrim('xyxtrimyyx', 'xy') | trim |
| chr(int) | text | 返回给定码点对应的单个字符 | chr(65) | A |
| convert(string, src_encoding, dest_encoding) | bytea | 将字节串在指定字符编码之间转换 | convert('text_in_utf8', 'UTF8', 'LATIN1') | ISO 8859-1 编码字节序列 |
| initcap(text) | text | 将每个单词首字母转为大写、其余转为小写 | initcap('hi thomas') | Hi Thomas |
| length(string) | int | 返回字符串的字符个数 | length('jose') | 4 |
| lpad(string, length [, fill]) | text | 在左侧填充字符至目标长度,超长则从右侧截断 | lpad('hi', 5, 'xy') | xyxhi |
| ltrim(string [, characters]) | text | 从开头删除包含于 characters 的最长前缀 | ltrim('zzzytrim', 'xyz') | trim |
| md5(string) | text | 计算字符串的十六进制 MD5 摘要 | md5('abc') | 900150983cd24fb0d6963f7d28e17f72 |
| repeat(string, number) | text | 将字符串重复拼接 number 次 | repeat('Pg', 4) | PgPgPgPg |
| replace(string, from, to) | text | 将所有匹配的 from 子串替换为 to | replace('abcdefabcdef', 'cd', 'XX') | abXXefabXXef |
| rpad(string, length [, fill]) | text | 在右侧填充字符至目标长度,超长则截断 | rpad('hi', 5, 'xy') | hixyx |
| rtrim(string [, characters]) | text | 从结尾删除包含于 characters 的最长后缀 | rtrim('trimxxxx', 'x') | trim |
| split_part(string, delimiter, field) | text | 按分隔符拆分并返回第 field 段(从 1 计数) | split_part('abc~@~def~@~ghi', '~@~', 2) | def |
| strpos(string, substring) | int | 返回子串首次出现的位置(原表误标 text,实为 int) | strpos('high', 'ig') | 2 |
| substr(string, from [, count]) | text | 按起始位置和可选长度抽取子串 | substr('alphabet', 3, 2) | ph |
| to_ascii(text [, encoding]) | text | 将兼容单字节编码文本映射为 ASCII | to_ascii('Karel') | Karel |
| to_hex(number int/bigint) | text | 将整数转换为小写十六进制文本 | to_hex(9223372036854775807) | 7fffffffffffffff |
| translate(string, from, to) | text | 逐字符将 from 中的字符映射替换为 to 中对应位置字符 | translate('12345', '14', 'ax') | a23x5 |
PostgreSQL 格式化与类型转换函数一览
| 函数 | 返回类型 | 描述 | 示例 |
|---|---|---|---|
| to_char(timestamp, text) | text | 按格式模板将时间戳转换为字符串 | to_char(current_timestamp, 'HH12:MI:SS') |
| to_char(interval, text) | text | 按格式模板将时间间隔转换为字符串 | to_char(interval '15h 2m 12s', 'HH24:MI:SS') |
| to_char(int, text) | text | 按数字模板将整型转换为字符串 | to_char(125, '999') |
| to_char(double precision, text) | text | 按数字模板将浮点型转换为字符串 | to_char(125.8::real, '999D9') |
| to_char(numeric, text) | text | 按数字模板将高精度数值转换为字符串 | to_char(-125.8, '999D99S') |
| to_date(text, text) | date | 按模板将字符串解析为日期 | to_date('05 Dec 2000', 'DD Mon YYYY') |
| to_number(text, text) | numeric | 按模板将格式化字符串解析为数值 | to_number('12,454.8-', '99G999D9S') |
| to_timestamp(text, text) | timestamp with time zone | 按模板将字符串解析为带时区时间戳 | to_timestamp('05 Dec 2000', 'DD Mon YYYY') |
| to_timestamp(double precision) | timestamp with time zone | 将 UNIX 纪元秒转换为带时区时间戳 | to_timestamp(1284352323) |
运行 PostgreSQL 聚合、数学/三角、字符串及格式化转换核心算例离线实测
"""PostgreSQL 常用函数离线实验:验证聚合、数学、三角、字符串与格式化/类型转换函数核心算例。"""
from datetime import datetime
import hashlib
import json
import math
import platform
import sqlite3
def build_db() -> sqlite3.Connection:
conn = sqlite3.connect(":memory:")
conn.execute("PRAGMA foreign_keys = ON;")
conn.executescript(
"""
CREATE TABLE COMPANY (
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS TEXT,
SALARY REAL
);
INSERT INTO COMPANY VALUES
(1, 'Paul', 32, 'California', 20000.0),
(2, 'Allen', 25, 'Texas', 15000.0),
(3, 'Teddy', 23, 'Norway', 20000.0),
(4, 'Mark', 25, 'Rich-Mond', 65000.0),
(5, 'David', 27, 'Texas', 85000.0),
(6, 'Kim', 22, 'South-Hall', 45000.0),
(7, 'James', 24, 'Houston', 10000.0);
"""
)
return conn
def run() -> dict:
conn = build_db()
cases = []
agg = conn.execute(
"""
SELECT
COUNT(*),
MAX(SALARY),
MIN(SALARY),
ROUND(AVG(SALARY), 2),
SUM(SALARY),
json_group_array(NAME)
FROM (SELECT NAME, SALARY FROM COMPANY ORDER BY ID);
"""
).fetchone()
exp1 = {
"count": 7,
"max_salary": 85000.0,
"min_salary": 10000.0,
"avg_salary": 37142.86,
"sum_salary": 260000.0,
"names_array": ["Paul", "Allen", "Teddy", "Mark", "David", "Kim", "James"],
}
act1 = {
"count": agg[0],
"max_salary": agg[1],
"min_salary": agg[2],
"avg_salary": agg[3],
"sum_salary": agg[4],
"names_array": json.loads(agg[5]),
}
cases.append(
{
"name": "aggregate_builtin_functions",
"summary": "验证 COUNT、MAX、MIN、AVG、SUM 与数组聚合等价输出",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
}
)
m = conn.execute(
"""
SELECT
abs(-17.4),
ceil(-42.8),
floor(-42.8),
mod(9, 4),
power(9.0, 3.0),
round(42.4),
round(42.438, 2),
sign(-8.4),
trunc(42.8),
log10(100.0),
log(2.0, 64.0),
round(sqrt(2.0), 6),
round(exp(1.0), 6),
round(ln(2.0), 6),
round(pi(), 6),
round(radians(45.0), 6),
round(degrees(0.5), 6),
round(sin(0.0), 6),
round(cos(0.0), 6),
round(tan(0.0), 6),
round(acos(1.0), 6),
round(asin(0.0), 6),
round(atan(0.0), 6),
round(atan2(0.0, 1.0), 6)
"""
).fetchone()
exp2 = {
"abs": 17.4,
"cbrt_27": 3.0,
"ceil": -42.0,
"floor": -43.0,
"mod": 1.0,
"power": 729.0,
"round_int": 42.0,
"round_2": 42.44,
"sign": -1,
"trunc": 42.0,
"log10": 2.0,
"log2_64": 6.0,
"sqrt2": 1.414214,
"exp1": 2.718282,
"ln2": 0.693147,
"pi": 3.141593,
"rad45": 0.785398,
"deg05": 28.64789,
"trig_zeros": [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
"cot_pi_over_4": 1.0,
}
act2 = {
"abs": m[0],
"cbrt_27": round(math.cbrt(27.0), 6),
"ceil": m[1],
"floor": m[2],
"mod": m[3],
"power": m[4],
"round_int": m[5],
"round_2": m[6],
"sign": m[7],
"trunc": m[8],
"log10": m[9],
"log2_64": m[10],
"sqrt2": m[11],
"exp1": m[12],
"ln2": m[13],
"pi": m[14],
"rad45": m[15],
"deg05": m[16],
"trig_zeros": [m[17], m[18], m[19], m[20], m[21], m[22], m[23]],
"cot_pi_over_4": round(1.0 / math.tan(math.pi / 4.0), 6),
}
cases.append(
{
"name": "math_and_trig_functions",
"summary": "利用 SQLite 3.53 内置数学引擎与标准库核对 21 项数学函数及 8 项三角函数典型值",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
}
)
s = conn.execute(
"""
SELECT
'Post' || 'greSQL',
length('jose'),
octet_length('jose'),
lower('TOM'),
upper('tom'),
instr('Thomas', 'om'),
substr('Thomas', 2, 3),
trim('xTomxx', 'x'),
unicode('x'),
char(65),
ltrim('zzzytrim', 'xyz'),
rtrim('trimxxxx', 'x'),
replace('abcdefabcdef', 'cd', 'XX'),
instr('high', 'ig'),
substr('alphabet', 3, 2)
"""
).fetchone()
exp3 = {
"concat": "PostgreSQL",
"char_length": 4,
"octet_length": 4,
"bit_length": 32,
"lower": "tom",
"upper": "TOM",
"position_om": 3,
"substring_hom": "hom",
"trim_x": "Tom",
"ascii_x": 120,
"chr_65": "A",
"ltrim": "trim",
"rtrim": "trim",
"replace": "abXXefabXXef",
"strpos_ig": 2,
"substr_ph": "ph",
"repeat_pg": "PgPgPgPg",
"split_part_2": "def",
"to_hex_max64": "7fffffffffffffff",
"translate": "a23x5",
"md5_abc": "900150983cd24fb0d6963f7d28e17f72",
}
act3 = {
"concat": s[0],
"char_length": s[1],
"octet_length": s[2],
"bit_length": s[2] * 8,
"lower": s[3],
"upper": s[4],
"position_om": s[5],
"substring_hom": s[6],
"trim_x": s[7],
"ascii_x": s[8],
"chr_65": s[9],
"ltrim": s[10],
"rtrim": s[11],
"replace": s[12],
"strpos_ig": s[13],
"substr_ph": s[14],
"repeat_pg": "Pg" * 4,
"split_part_2": "abc~@~def~@~ghi".split("~@~")[1],
"to_hex_max64": format(9223372036854775807, "x"),
"translate": "12345".translate(str.maketrans("14", "ax")),
"md5_abc": hashlib.md5(b"abc").hexdigest(),
}
cases.append(
{
"name": "string_functions_and_concat",
"summary": "验证 || 拼接、大小写、长度、裁剪、替换、定位、切片、重复、十六进制与 MD5 等核心字符串运算",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
}
)
conv_row = conn.execute(
"""
SELECT
printf('%3d', 125),
printf('%.1f', 125.8),
datetime(1284352323, 'unixepoch')
"""
).fetchone()
parsed_date = datetime.strptime("05 Dec 2000", "%d %b %Y").strftime("%Y-%m-%d")
exp4 = {
"int_to_str": "125",
"real_to_str": "125.8",
"epoch_to_utc": "2010-09-13 04:32:03",
"str_to_date": "2000-12-05",
}
act4 = {
"int_to_str": conv_row[0],
"real_to_str": conv_row[1],
"epoch_to_utc": conv_row[2],
"str_to_date": parsed_date,
}
cases.append(
{
"name": "format_and_conversion_equivalents",
"summary": "核对数字格式化、UNIX 纪元秒转时间戳(1284352323 -> 2010-09-13 04:32:03 UTC)及英文日期解析",
"expected": exp4,
"actual": act4,
"passed": act4 == exp4,
}
)
conn.close()
return {
"version": f"CPython {platform.python_version()} / SQLite {sqlite3.sqlite_version} (offline PostgreSQL verifier)",
"cases": cases,
}
if __name__ == "__main__":
print(json.dumps(run(), ensure_ascii=False, indent=2))
- 验证 7 行 COMPANY 聚合统计、21 项数学与 8 项三角函数值、21 项字符串运算及 UNIX 纪元/英文日期解析全部命中预期。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:fd2882fc13c8ef3f78e88245c58f0841e9709f264ae372a48b6123ff78200b46
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:17f0fa8e28b65e2fd111751019937898a0fb1c315bcbb57d948eaa33ee8cc035
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 PostgreSQL 中,`char_length('中国')` 与 `octet_length('中国')` 在 UTF-8 编码下返回值是否相同?
展开参考解答
不同。`char_length('中国')` 返回字符数 `2`,而 `octet_length('中国')` 返回 UTF-8 字节数 `6`(每个汉字占 3 字节)。