当前位置: 代码网 > it编程>数据库>MsSqlserver > PGSQL常见命令行与函数实例详解

PGSQL常见命令行与函数实例详解

2025年11月03日 MsSqlserver 我要评论
postgresql 常用命令行与内置函数详解一、postgresql 命令行工具(psql)详解1. 数据库连接与基本操作(1)连接数据库# 基本连接(使用当前系统用户)psql# 连接指定数据库p

postgresql 常用命令行与内置函数详解

一、postgresql 命令行工具(psql)详解

1. 数据库连接与基本操作

(1)连接数据库
# 基本连接(使用当前系统用户)
psql
# 连接指定数据库
psql -d mydatabase
# 连接指定用户和数据库
psql -u username -d mydatabase
# 连接远程数据库
psql -h hostname -p 5432 -u username -d mydatabase
# 连接并执行sql文件
psql -d mydatabase -f script.sql
# 连接并执行单条命令
psql -d mydatabase -c "select version();"
(2)连接参数说明
参数说明示例
-d数据库名-d postgres
-u用户名-u postgres
-h主机地址-h localhost
-p端口号-p 5432
-w强制密码提示-w
-f执行sql文件-f init.sql
-c执行命令-c "select 1"

2. psql 内部元命令(反斜杠命令)

(1)数据库操作
-- 列出所有数据库
\l
\l+
-- 连接/切换数据库
\c database_name
\connect database_name
-- 创建数据库
create database newdb;
-- 删除数据库
drop database olddb;
(2)表操作
-- 列出当前数据库所有表
\dt
\dt+
-- 描述表结构
\d table_name
\d+ table_name
-- 列出所有索引
\di
\di+
-- 列出所有序列
\ds
\ds+
(3)模式操作
-- 列出所有模式
\dn
\dn+
-- 设置搜索路径
set search_path to schema1, schema2;
-- 查看当前搜索路径
show search_path;
(4)用户和权限
-- 列出所有用户/角色
\du
\du+
-- 查看当前用户
select current_user;
-- 查看用户权限
\dp table_name
\z table_name
(5)信息查询
-- 查看服务器版本
select version();
-- 查看连接信息
\conninfo
-- 查看当前数据库
select current_database();
-- 查看当前模式
select current_schema();
(6)输出和格式控制
-- 扩展显示(行转列)
\x on
\x auto
\x off
-- 设置输出格式
\a (对齐切换)
\f (字段分隔符)
-- 计时开关
\timing on
\timing off
-- 输出到文件
\o filename.txt
\o

3. 实用元命令大全

命令功能示例
\?查看所有元命令帮助\?
\hsql命令帮助\h create table
\q退出psql\q
\!执行系统命令\! ls -l
\g再次执行上次查询\g
\s查看命令历史\s
\e使用编辑器编辑查询\e
\i执行外部sql文件\i /path/to/file.sql
\copy导入导出数据\copy table to 'file.csv' csv

二、postgresql 内置函数详解

1. 数学函数

(1)基本数学运算
-- 绝对值
select abs(-15); -- 15
-- 四舍五入
select round(3.14159, 2); -- 3.14
select round(123.456); -- 123
-- 取整函数
select ceil(3.14); -- 4 (向上取整)
select floor(3.14); -- 3 (向下取整)
select trunc(3.14159, 2); -- 3.14 (截断)
-- 幂运算
select power(2, 3); -- 8
select sqrt(25); -- 5 (平方根)
select cbrt(27); -- 3 (立方根)
-- 对数函数
select ln(10); -- 自然对数
select log(100); -- 以10为底对数
(2)三角函数
select pi(); -- 3.14159265358979
select sin(pi()/2); -- 1
select cos(0); -- 1
select tan(pi()/4); -- 1
select degrees(pi()); -- 180 (弧度转角度)
select radians(180); -- 3.14159 (角度转弧度)
(3)随机数生成
select random(); -- 0-1之间的随机数
select setseed(0.5); -- 设置随机种子
-- 生成指定范围随机整数
select floor(random() * 100)::int; -- 0-99随机整数
select (random() * (max-min) + min)::int; -- min-max随机整数

2. 字符串函数

(1)字符串操作
-- 长度和位置
select length('hello'); -- 5
select position('l' in 'hello'); -- 3
select strpos('hello', 'l'); -- 3
-- 大小写转换
select upper('hello'); -- hello
select lower('hello'); -- hello
select initcap('hello world'); -- hello world
-- 修剪函数
select trim('  hello  '); -- 'hello'
select ltrim('  hello'); -- 'hello'
select rtrim('hello  '); -- 'hello'
select trim(both 'x' from 'xxhelloxx'); -- 'hello'
-- 填充函数
select lpad('hi', 5, '*'); -- '***hi'
select rpad('hi', 5, '*'); -- 'hi***'
(2)子字符串操作
-- 子字符串
select substring('hello world' from 2 for 5); -- 'ello '
select substr('hello world', 2, 5); -- 'ello '
-- 字符串替换
select replace('hello world', 'world', 'postgresql'); -- 'hello postgresql'
select translate('12345', '123', 'abc'); -- 'abc45'
-- 字符串分割
select split_part('a,b,c,d', ',', 2); -- 'b'
select string_to_array('a,b,c', ','); -- {a,b,c}
select array_to_string(array['a','b','c'], ','); -- 'a,b,c'
(3)格式化函数
-- 字符串连接
select concat('hello', ' ', 'world'); -- 'hello world'
select 'hello' || ' ' || 'world'; -- 'hello world'
-- 格式化输出
select format('hello %s, your balance is %s', 'john', 100.50);
-- 'hello john, your balance is 100.50'
-- 重复字符串
select repeat('*', 5); -- '*****'

3. 日期时间函数

(1)当前时间获取
-- 获取当前时间
select current_date; -- 当前日期
select current_time; -- 当前时间
select current_timestamp; -- 当前时间戳
select now(); -- 当前时间戳(同current_timestamp)
select localtimestamp; -- 本地时间戳
-- 带精度的当前时间
select current_time(2); -- 当前时间(2位小数秒)
select current_timestamp(3); -- 当前时间戳(3位小数秒)
(2)日期时间提取
-- extract函数
select extract(year from current_timestamp); -- 年份
select extract(month from current_timestamp); -- 月份
select extract(day from current_timestamp); -- 日期
select extract(hour from current_timestamp); -- 小时
select extract(minute from current_timestamp); -- 分钟
select extract(second from current_timestamp); -- 秒数
select extract(dow from current_timestamp); -- 星期几(0-6,周日=0)
select extract(doy from current_timestamp); -- 一年中的第几天
-- date_part函数(同extract)
select date_part('year', current_timestamp);
(3)日期时间运算
-- 日期加减
select current_date + interval '1 day'; -- 明天
select current_date - interval '1 week'; -- 一周前
select current_timestamp + interval '2 hours 30 minutes'; -- 2小时30分钟后
-- 年龄计算
select age('2000-01-01'::date); -- 从2000-01-01到现在的年龄
select age('2000-01-01'::date, '2020-01-01'::date); -- 两个日期之间的年龄
-- 日期截断
select date_trunc('hour', current_timestamp); -- 截断到小时
select date_trunc('day', current_timestamp); -- 截断到天
select date_trunc('month', current_timestamp); -- 截断到月
(4)日期时间格式化
-- to_char格式化
select to_char(current_timestamp, 'yyyy-mm-dd hh24:mi:ss'); -- '2023-01-01 14:30:00'
select to_char(current_timestamp, 'day, month dd, yyyy'); -- 'sunday, january 01, 2023'
select to_char(123.45, '999d99'); -- '123.45'
-- to_date和to_timestamp转换
select to_date('20230101', 'yyyymmdd'); -- 2023-01-01
select to_timestamp('20230101 143000', 'yyyymmdd hh24miss'); -- 2023-01-01 14:30:00

4. 条件函数

(1)条件判断
-- case表达式
select 
    name,
    salary,
    case 
        when salary > 100000 then 'high'
        when salary > 50000 then 'medium'
        else 'low'
    end as salary_level
from employees;
-- 简单case
select 
    product_type,
    case product_type
        when 'a' then 'type a'
        when 'b' then 'type b'
        else 'other'
    end as type_description
from products;
(2)空值处理
-- coalesce(返回第一个非空值)
select coalesce(null, null, 'default'); -- 'default'
select coalesce(email, 'n/a') from users; -- 如果email为null则返回'n/a'
-- nullif(相等返回null)
select nullif(5, 5); -- null
select nullif(5, 0); -- 5
-- greatest和least
select greatest(1, 5, 3); -- 5
select least(1, 5, 3); -- 1

5. 聚合函数

(1)基本聚合函数
-- 计数
select count(*) from table; -- 总行数
select count(distinct column) from table; -- 不重复计数
-- 求和与平均
select sum(salary) from employees;
select avg(salary) from employees;
-- 最大最小值
select max(salary) from employees;
select min(salary) from employees;
-- 统计信息
select stddev(salary) from employees; -- 标准差
select variance(salary) from employees; -- 方差
(2)高级聚合函数
-- 分组统计
select 
    department,
    count(*) as emp_count,
    avg(salary) as avg_salary,
    sum(salary) as total_salary
from employees 
group by department;
-- 字符串聚合
select 
    department,
    string_agg(name, ', ') as employees
from employees 
group by department;
-- 数组聚合
select 
    department,
    array_agg(name) as employees
from employees 
group by department;
-- json聚合
select 
    department,
    json_agg(json_build_object('name', name, 'salary', salary)) as employees
from employees 
group by department;

6. 窗口函数

(1)排名函数
-- 行号、排名、密集排名
select 
    name,
    salary,
    row_number() over (order by salary desc) as row_num,
    rank() over (order by salary desc) as rank,
    dense_rank() over (order by salary desc) as dense_rank
from employees;
-- 分区排名
select 
    department,
    name,
    salary,
    rank() over (partition by department order by salary desc) as dept_rank
from employees;
(2)前后值函数
-- lag和lead(访问前后行)
select 
    date,
    sales,
    lag(sales) over (order by date) as prev_sales,
    lead(sales) over (order by date) as next_sales
from sales_data;
-- first_value和last_value
select 
    date,
    sales,
    first_value(sales) over (order by date) as first_sales,
    last_value(sales) over (order by date) as last_sales
from sales_data;
(3)累计和移动平均
-- 累计计算
select 
    date,
    sales,
    sum(sales) over (order by date) as cumulative_sum,
    avg(sales) over (order by date) as cumulative_avg
from sales_data;
-- 移动平均
select 
    date,
    sales,
    avg(sales) over (order by date rows between 2 preceding and current row) as moving_avg_3
from sales_data;

7. json 函数(postgresql 9.3+)

(1)json创建和解析
-- 创建json
select json_build_object('name', 'john', 'age', 30);
select json_build_array(1, 2, 3);
-- 解析json
select json_extract_path('{"a": {"b": 1}}', 'a', 'b'); -- 1
select '{"name": "john"}'::json->>'name'; -- 'john'
select '{"ages": [10, 20, 30]}'::json->'ages'->>1; -- '20'
(2)json聚合
-- 行转json
select row_to_json(employees) from employees where id = 1;
-- json聚合
select 
    department,
    json_agg(json_build_object('name', name, 'salary', salary)) as employees
from employees 
group by department;

三、实用sql示例

1. 数据备份和恢复

# 备份单个数据库
pg_dump -u username -d mydatabase -f backup.sql
# 备份所有数据库
pg_dumpall -u username -f alldb_backup.sql
# 压缩备份
pg_dump -u username -d mydatabase | gzip > backup.sql.gz
# 恢复数据库
psql -u username -d mydatabase -f backup.sql
# 恢复压缩备份
gunzip -c backup.sql.gz | psql -u username -d mydatabase

2. 性能分析

-- 查看查询计划
explain select * from large_table where id = 1000;
explain analyze select * from large_table where id = 1000;
-- 查看表大小和索引
select 
    schemaname,
    tablename,
    tableowner,
    tablesize,
    indexsize
from pg_tables 
where schemaname = 'public';
-- 查看长查询
select 
    pid, 
    now() - pg_stat_activity.query_start as duration, 
    query 
from pg_stat_activity 
where state = 'active' 
order by duration desc;

3. 实用管理查询

-- 查看锁信息
select 
    locktype, 
    relation::regclass, 
    mode, 
    granted 
from pg_locks 
where relation = 'mytable'::regclass;
-- 查看连接数
select 
    datname, 
    count(*) as connections 
from pg_stat_activity 
group by datname;
-- 查看表统计信息
select 
    schemaname,
    tablename,
    seq_scan,
    seq_tup_read,
    idx_scan,
    idx_tup_fetch
from pg_stat_user_tables;

四、总结

postgresql 提供了丰富的命令行工具和内置函数,使得数据库管理和数据操作变得非常高效。关键点包括:

  1. psql命令行:熟练掌握连接参数和元命令,提高管理效率
  2. 数学函数:处理数值计算和统计分析
  3. 字符串函数:文本处理和格式化输出
  4. 日期时间函数:时间计算和格式化
  5. 聚合函数:数据统计和分组分析
  6. 窗口函数:高级分析和排名计算
  7. json函数:处理半结构化数据

相关文献

【数据库知识】postgresql介绍

到此这篇关于pgsql常见命令行与函数实例详解的文章就介绍到这了,更多相关pgsql常见命令内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com