PostgreSql常用SQL大全

DDL库/表结构(建库,建表,改字段,删表)

plsql 复制代码
# 创建数据库
create database test_db

# 建表
create table user(
  id serial primary key,
  name varchar(32) not null,
  age int null
)

# 修改表字段
alter table user add column email varchar(50) # 新增字段
alter table user drop column email # 删除字段
alter table user alter column name type varchar(50) # 修改字段类型

# 删除表
drop table user

DML增删查改

plsql 复制代码
# 新增 insert
insert into user (name,age) values ('张三',22)

insert into user (name,age) values ('张三',22),('李四',22)

# 修改 update
update user set age=23 where id=1

update user set age=23 where id in (1,2,3)

# 删除 delete
delete from user where id=1

truncate table user # 清空全表
plsql 复制代码
# 查询 select
select * from user # 全查
select id,name from user # 指定字段
select * from user where id=1 # 等于
select * from user where age between 20 and 30 # 区间 between and
select * from user where id in (1,2,3) # in多选
select * from user where age is null # 空
select * from user where age is not null # 非空
select * from user where age>20 and age<40
select * from user where age=20 or age=40

# 模糊匹配 like 区分大小写
select * from user where name like '张%' 
select * from user where name like '%张%'
select * from user where name like '%张'

# 模糊匹配 ilike 不区分大小写
select * from user where name ilike '%zhang%'

# 排序 order by
select * from user order by age asc # 升序
select * from user order by age desc # 降序

# 分页 limit offset
select * from user limit 3 offset 0 # 前3条
select * from user limit 3 offset 4 # 第 5~7 条

联表查询

plsql 复制代码
# 内连接 inner join
select user.id,user.name,todos.title,todos.is_finish from user inner join todos on user.id = todos.id

# 左连接 left join
select user.id,user.name,todos.title,todos.is_finish from user left join todos on user.id = todos.id

聚合+分组

plsql 复制代码
# 聚合:总数量,平均年龄,最大最小
select count(*),avg(age),max(age),min(age) from user

# 分组后过滤
select user.name,count(id) todo_num
from user
left join todo on user.id = todo.user_id
group by user.id,user.name
having count(todo.id) > 2

子查询

plsql 复制代码
select * from user where id in (select user_id from todo where is_finnish=true)

CASE WHEN

plsql 复制代码
select name,age,case
when age < 25 then '青年'
when age >=25 and age <35 then '壮年'
else '中年'
end as age_type
from user

日期相关SQL

plsql 复制代码
select * from user where extract(year from create_time)=2025; # 查询2025年创建的用户
select * from user where extract(month from create_time)=3; # 某月的数据

其他

plsql 复制代码
# 字符串拼接
select concat(name,'-',age) from user

# 去重
select distinct name from user
相关推荐
笃行35011 小时前
金仓数据库数据安全双防线:静态存储加密与传输加密实战
数据库
笃行35011 小时前
金仓数据库物理备份实战:sys_rman 全流程演练与误覆盖抢救
数据库
笃行35011 小时前
金仓数据库逻辑备份实战:从全库导出到 Schema 替换的完整闭环
数据库
SelectDB1 天前
阶跃星辰基于 SelectDB 构建 PB 级 Agent 可观测平台
大数据·数据库·aigc
这个DBA有点耶1 天前
GROUP BY优化全解:如何写出既不丢数据又飞快的分组查询
数据库·mysql·架构
掉头发的王富贵2 天前
【StarRocks】极限十分钟入门StarRocks
数据库·sql·mysql
Nturmoils2 天前
WHERE 条件别凭习惯写,常用查询先跑一遍
数据库
Databend2 天前
在 AWS 中国峰会逛了一天,我在 Databend 展台看到了 Agent 数据基础设施的新思路
数据库·人工智能·agent
ClouGence4 天前
Oracle 数据同步为什么会出现数据不一致?长事务是常被忽略的原因
数据库·后端·oracle