SQL(Structured Query Language)中文全称为”结构化查询语句“,在 1986 年成为 ANSI(American National Standards Institute 美国国家标准化组织)的一项标准,在 1987 年成为国际标准化组织(ISO)标准。
SQL 是一种数据库查询和程序设计语言,用于存取数据以及查询、更新和管理关系数据库系统。简单理解就是对我们数据库和数据库中的表进行”增删改查“操作的编程语言。虽然 SQL 是一门标准的计算机语言,但由于数据库类型繁多,存在着多种不同版本的 SQL 语言。为了与 ANSI 标准相兼容,它们必须以相似的方式共同地来支持一些主要的命令(比如 SELECT、UPDATE、DELETE、INSERT、WHERE 等等),下列为 postgresql 数据库操作示例。
按照其功能,主要分为以下几种类型:
--转义
select E'I\'m student';
select $$I'm student$$;
select * from employees;
select version() as "数据库版本";
select distinct department_id,department_name from departments;
select first_name as "名字",last_name "姓氏" --我是单行注释
/*我是
多行
注释*/ from employees;
select * from employees where employee_id >= 150;
select * from employees where employee_id between 150 and 160;
select * from employees where employee_id in (150,160,170);
select last_name from employees where last_name like 'S%';
select last_name from employees where last_name like 'S_i%';
select last_name from employees where last_name like 'S#%%' escape '#';
select last_name from employees where last_name like 'S\%%';
select last_name from employees where last_name not like 'S%';
select last_name from employees where last_name not ilike '%S%';
select * from employees where commission_pct is null;
select * from employees where commission_pct is not null;
select * from employees where commission_pct isnull;
select * from employees where commission_pct notnull;
select * from employees where commission_pct is distinct from null;
select * from employees where commission_pct is not distinct from null;
select * from employees where first_name = 'Steven' and last_name = 'King';
select 1=1 or 1/0=1;
select 1=2 and 1/0=1;
select * from employees where (hire_date > '2008-01-01' or salary < 5000) and commission_pct is null;
select employee_id,first_name,last_name,hire_date,salary,manager_id from employees order by first_name;
select employee_id,first_name,last_name,hire_date,salary,manager_id from employees order by first_name asc;
select employee_id,first_name,last_name,hire_date,salary,manager_id from employees order by first_name desc;
select employee_id,first_name,last_name,hire_date,salary,manager_id from employees order by manager_id desc;
select employee_id,first_name,last_name,hire_date,salary,manager_id from employees order by manager_id nulls first;
select employee_id,first_name,last_name,hire_date,salary,manager_id from employees order by manager_id nulls last;
--标椎sql获取前10条记录
select first_name,last_name,salary from employees order by salary fetch first 10 rows only;
--扩展 limit 获取前10条记录
select first_name,last_name,salary from employees order by salary limit 10;
--获取前10条数据中有相同数据时
select first_name,last_name,salary from employees order by salary fetch first 10 rows with ties;
--标椎sql分页
select first_name,last_name,salary from employees order by salary offset 0 rows fetch first 10 rows only;
select first_name,last_name,salary from employees order by salary offset 10 rows fetch first 10 rows only;
select first_name,last_name,salary from employees order by salary offset 20 rows fetch first 10 rows only;
……
--扩展 limit 分页
select first_name,last_name,salary from employees order by salary offset 0 limit 10;
select first_name,last_name,salary from employees order by salary offset 10 limit 10;
select first_name,last_name,salary from employees order by salary offset 20 limit 10;
……
--查找 employees 表中月薪第二高的所有员工
select first_name,last_name,salary from employees where salary != (select max(salary) from employees) order by salary desc fetch first 1 rows with ties;
select count(*),count(manager_id) from employees;
--逗号(,)为分隔符聚合字符串,并去重倒序显示
select string_agg(distinct first_name,',' order by first_name desc) from employees;
select department_id,count(*) from employees group by department_id order by department_id;
select commission_pct,count(*) from employees group by commission_pct order by commission_pct;
select department_id,count(*) from employees group by department_id having count(*) > 10 order by department_id;
--哪些部门有超过2人的员工工资大于10000
select department_id,count(*) from employees where salary > 10000 group by department_id having count(*) > 2;
--对所有产品,所有年份进行汇总小计,并按产品进行所有年份合计总计。
select coalesce(item,'所有产品') "产品",coalesce(year,'所有年份') "年份",sum(quantity) from sales group by rollup (item,year);
select coalesce(item,'所有产品') "产品",coalesce(year,'所有年份') "年份",sum(quantity) from sales group by grouping sets((item,year),(item),());
--对所有产品,所有年份进行汇总小计,并按产品进行所有年份合计总计,按年份进行所有产品合计总计。
select coalesce(item,'所有产品') "产品",coalesce(year,'所有年份') "年份",sum(quantity) from sales group by cube (item,year);
select coalesce(item,'所有产品') "产品",coalesce(year,'所有年份') "年份",sum(quantity) from sales group by grouping sets((item,year),(item),(year),());
--区分源空值及分组空值
select item "产品",year "年份",sum(quantity),grouping(item),grouping(year) from sales group by cube (item,year);
--内连接
select d.department_id,e.first_name,d.department_name from employees e join departments d on e.department_id = d.department_id;
--左外连接
select d.department_id,e.first_name,d.department_name from employees e left join departments d on e.department_id = d.department_id;
--右外连接
select d.department_id,e.first_name,d.department_name from employees e right join departments d on e.department_id = d.department_id;
--全外连接
select d.department_id,e.first_name,d.department_name from employees e full join departments d on e.department_id = d.department_id;
--交叉连接
select d.department_id,e.first_name,d.department_name from employees e cross join departments d;
--交叉连接打印九九乘法表
select concat(t1,'*',t2,'=',t1*t2) from generate_series(1,9) t1 cross join generate_series(1,9) t2;
--USING 替代 ON 子句
select d.department_id,e.first_name,d.department_name from employees e join departments d using(department_id);
--自然连接
select d.department_id,e.first_name,d.department_name from employees e natural join departments d;
--case 条件及等值
select employee_id,first_name,last_name,
case
when salary < 5000 then '低收入'
when salary between 5000 and 10000 then '中收入'
else '高收入'
end as "薪资",
case department_id
when 110 then '管理'
when 100 then '研发'
else '其他'
end as "部门"
from employees;
--行转列两种写法
select count(case department_id when 10 then 1 end) as "部门10",
count(case department_id when 20 then 1 end) as "部门20",
count(case department_id when 30 then 1 end) as "部门30",
count(case department_id when 40 then 1 end) as "部门40",
count(*) filter (where department_id=50) as "部门50"
from employees ;
--部门编号为50的则显示null,其他部门编号正常显示,销售提成为 null 的显示 999
select employee_id,first_name,last_name,nullif(department_id,50),coalesce(commission_pct,999) from employees;
--算数运算符
select 2+1 "加",2-1 "减",2*1 "乘",4/2 "除",4%3 "求余",2^3 "求幂",|/9 "平方根",||/8 "立方根",3! as "阶乘",!!3 "阶乘2",@ -5 "绝对值";
--绝对值函数
select abs(-5);
--取整函数
select ceil(-12.3) "向上取整",floor(-12.3) "向下取整",round(-12.5) "四舍五入取整",trunc(-12.3) "向零取整";
--乘方开方函数
select power(2,3) "乘方",sqrt(4) "平方根",cbrt(8) "立方根";
--整数商余数函数
select div(7,3) "整数商",mod(7,3) "余数";
--π
select pi();
--随机数函数(0-1)
select random();
select first_name from employees order by random() limit 1;
--字符串连接
select concat(t1,'*',t2,'=',t1*t2) from generate_series(1,9) t1 cross join generate_series(1,9) t2;
select t1||'*'||t2||'='||t1*t2 from generate_series(1,9) t1 cross join generate_series(1,9) t2;
--字符串拼接(自定义分隔符)
select concat_ws('#',1,2,3,4);
--字符串长度
select bit_length('瀚高') "比特数",length('瀚高') "字符数",octet_length('瀚高') "字节数";
--大小写转换
select lower('HighgGo db') "小写",upper('HighgGo db') "大写",initcap('HighgGo db') "首字母大写";
--字符串反转
select reverse('上海自来水');
--获取当前时间
select current_date,current_time,current_timestamp,clock_timestamp(),localtimestamp,now(),statement_timestamp();
--to_date 字符串转时间函数
select to_date('2023/01/10','YYYY/MM/DD');
--to_char 其他类型转字符串函数
select to_char(current_timestamp,'HH24:MI:SS'),to_char(interval '5h 12m 30s','HH12:MI:SS'),to_char(-125.8,'999D99');
--to_number 字符串转数字函数
select to_number('¥125.8','L999D9');
--隐式转换
select 1+'2','todo: '||current_timestamp;
--子查询
select * from employees where salary >= (select avg(salary) from employees);
--IN
select * from departments where department_id in (select distinct department_id from employees where hire_date >= '2008-01-01');
--ALL
select * from departments where department_id in (select distinct department_id from employees where hire_date >= '2008-01-01');
等价
select * from employees where salary > (select max(salary) from employees where department_id = 80);
--ANY(SOME)
select * from employees where salary > any(select salary from employees where department_id = 80);
select * from employees where salary > some(select salary from employees where department_id = 80);
等价
select * from employees where salary > (select min(salary) from employees where department_id = 80);
--查询每个部门的总工资(关联子查询)
select d.department_name,(select sum(salary) from employees where department_id = d.department_id) from departments d;
--查询大于所在部门平均公司的员工信息(关联子查询)
select * from employees e where salary > (select avg(salary) from employees where department_id = e.department_id);
--横向子查询
select d.department_name,t.sum_sal from departments d join lateral (select sum(salary) sum_sal from employees where department_id = d.department_id) t on true;
--EXTSTS
select * from departments d where exists(select 1 from employees where department_id = d.department_id and hire_date > date '2008-01-01');
--18 和 19 年的所有优秀员工(并集)
select emp_id from excellent_emp where year = 2018
union all
select emp_id from excellent_emp where year = 2019;
--18 和 19 年都是优秀员工的员工(交集)
select emp_id from excellent_emp where year = 2018
intersect all
select emp_id from excellent_emp where year = 2019;
--19 年新晋优秀员工(差集)
select emp_id from excellent_emp where year = 2019
except all
select emp_id from excellent_emp where year = 2018;
--优先级
select * from (values(1)) t1
union all
select * from (values(1)) t2
intersect
select * from (values(1)) t3;
(select * from (values(1)) t1
union all
select * from (values(1)) t2)
intersect
select * from (values(1)) t3;
--查询部门平均薪资
with department_avg(department_id,avg_sal) as (
select department_id,avg(salary) avg_sal
from employees group by department_id
)
select d.department_name,da.avg_sal
from departments d
join department_avg da
using(department_id);
--查询部门组织架构
with recursive emp_path(emp_id,emp_name,path) as (
select employee_id,first_name||','||last_name,first_name||','||last_name
from employees
where manager_id is null
union all
select employee_id,first_name||','||last_name,path||'->'||first_name||','||last_name
from employees e
join emp_path p on(e.manager_id = p.emp_id)
)
select * from emp_path;
--显示每个部门员工信息及其平均薪资
select employee_id,first_name,last_name,department_id,salary,avg(salary) over(partition by department_id) from employees;
--移动平均值
select employee_id,first_name,last_name,department_id,salary,avg(salary) over(partition by department_id rows between 1 preceding and 1 following) from employees;
--薪资排序
select employee_id,first_name,last_name,department_id,salary,
row_number() over(order by salary desc),
rank() over(order by salary desc),
dense_rank() over(order by salary desc),
percent_rank() over(order by salary desc),
cume_dist() over(order by salary desc),
ntile(5) over(order by salary desc)
from employees;
等价
select employee_id,first_name,last_name,department_id,salary,
row_number() over w,
rank() over w,
dense_rank() over w,
percent_rank() over w,
cume_dist() over w,
ntile(5) over w
from employees window w as (order by salary desc);
--取值窗口函数
select employee_id,first_name,last_name,department_id,salary,
first_value(salary) over w,
last_value(salary) over (order by salary desc rows between unbounded preceding and unbounded following),
nth_value(salary,3) over (order by salary desc rows between unbounded preceding and unbounded following),
lag(salary,1) over w,
lead(salary,1) over w
from employees window w as (order by salary desc);
--单行插入
insert into dept(department_id,department_name) values(1,'Adminstration');
insert into dept values(2,'Marketing');
--多行插入
insert into emp values
(200,'Jennifer','Whalen','2020-01-01',4400.00,NULL,1),
(201,'Michael','Hartstein','2020-02-02',13000.00,NULL,2),
(202,'Pat','Fay',default,6000.00,201,2);
--复制数据
create table emp1 (like emp);
insert into emp1 select * from emp;
--返回插入数据
insert into dept values (30,'Purchasing') returning department_id,department_name;
--单表更新
update emp set salary = salary + 1000,department_id = 2 where employee_id = 200;
--跨表更新
update emp1 set
salary = emp.salary,
department_id = emp.department_id,
manager_id = emp.manager_id
from emp where emp1.employee_id = emp.employee_id;
--返回更新后的数据
update emp set salary = salary + 1000,department_id = 2 where employee_id = 200
returning first_name,last_name,salary;
--单表删除
delete from emp1 where employee_id = 201;
--跨表删除
delete from emp1 using emp where emp1.employee_id = emp.employee_id;
等价
delete from emp1 where emp1.employee_id in (select employee_id from emp);
--返回被删除的数据
delete from emp1 returning *;
--主键冲突不做处理
insert into emp values (200,'Jennifer','Whalen','2020-01-01',4400.00,NULL,1)
on conflict (employee_id) do nothing;
--主键冲突更新目标数据
insert into emp values (200,'Jennifer','Whalen','2020-01-01',4400.00,NULL,1)
on conflict on constraint emp_pkey
do update set
first_name = EXCLUDED.first_name,
last_name = EXCLUDED.last_name,
hire_date = EXCLUDED.hire_date,
salary = EXCLUDED.salary,
manager_id =EXCLUDED.manager_id,
department_id = EXCLUDED.department_id;
--deletes 通用表达式
with deletes as (
delete from employees
where employee_id = 206
returning *
)
insert into employees_history
select * from deletes;
table employees_history;
--insert 通用表达式
with inserts as (
insert into employees
values
(206,'William','Gietz','WGIETZ','515.123.8181','2002-06-07','AC_ACCOUNT',8800.00,NULL,205,110)
returning *
)
insert into employees_history
select * from inserts;
table employees_history;
--update 通用表达式
delete from employees_history; -- 清除历史记录
with updates as (
update employees
set salary = salary + 500 where employee_id = 206
returning *
)
insert into employees_history
select * from employees where employee_id = 206;
table employees_history;
CREATE DATABASE name;
DROP DATABASE name;
ALTER DATABASE name ALLOW_CONNECTIONS true|false;
ALTER DATABASE name CONNECTION LIMIT connlimit;
ALTER DATABASE name CONNECTION IS_TEMPLATE true|false;
ALTER DATABASE name RENAME TO new_name;
ALTER DATABASE name OWNER TO new_owner;
ALTER DATABASE name SET TABLESPACE new_tablespace;
ALTER DATABASE name SET configuration_parameter {TO|=} {value|DEFAULT};
ALTER DATABASE name SET configuration_parameter FROM CURRENT;
ALTER DATABASE name RESET configuration_parameter;
ALTER DATABASE name RESET ALL;
CREATE ROLE|USER role_name;
DROP ROLE|USER role_name;
ALTER ROLE|USER role_name WITH PASSWORD 'password';
ALTER ROLE|USER role_name WITH PASSWORD NULL;
ALTER ROLE|USER role_name VALID UNTIL 'May 4 12:00:00 2015 +1';
ALTER ROLE|USER role_name VALID UNTIL 'infinity';
ALTER ROLE|USER role_name CREATEROLE CREATEDB;
ALTER ROLE|USER role_name SET maintenance_work_mem = 100000;
ALTER ROLE|USER role_name {IN DATABASE name} SET configuration_parameter {TO|=} {value|DEFAULT};
ALTER ROLE|USER role_name {IN DATABASE name} SET configuration_parameter FROM CURRENT;
ALTER ROLE|USER role_name {IN DATABASE name} RESET configuration_parameter;
ALTER ROLE|USER role_name {IN DATABASE name} RESET ALL;
CREATE SCHEMA schema_name;
DROP SCHEMA schema_name;
ALTER SCHEMA schema_name RENAME TO new_name;
ALTER SCHEMA schema_name OWNER TO new_owner;
CREATE TABLE table_name;
DROP TABLE table_name;
ALTER TABLE table_name RENAME TO new_name;
ALTER TABLE table_name SET SCHEMA new_schema;
ALTER TABLE table_name OWNER TO role_name;
ALTER TABLE table_name SET TABLESPACE tablespace_name;
ALTER TABLE table_name ADD column_name datatype;
ALTER TABLE table_name DROP column_name;
ALTER TABLE table_name ALTER column_name TYPE datatype;
ALTER TABLE table_name RENAME column_name TO new_column_name;
ALTER TABLE table_name ALTER column_name {SET|DROP} NOT NULL;
ALTER TABLE table_name ALTER column_name SET DEFAULT expression;
ALTER TABLE table_name RENAME CONSTRAINT constraint_name TO new_constraint_name;
ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY(id);
ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE(id);
ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK(id > 100);
ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY(id) REFERENCES reftable(id);
ALTER TABLE table_name DROP CONSTRAINT constraint_name;
……
……
--授权cc用户连接数据库syd
grant connect on database syd to cc;
--授权cc访问syd模式权限
grant usage on schema syd to cc;
--把syd用户的权限授予用户cc
grant syd to cc;
--授权syd用户可以访问syd模式下的syd表
grant select,insert,update,delete on syd.syd to syd;
--授权syd用户可以访问syd模式下的所有表
grant select,insert,update,delete on all tables in schema syd to syd;
--授权syd用户可以更新syd模式下的syd表的name列
grant update (name) on syd.syd to syd;
--授予syd用户对syd模式下的syd表,查看更新name、age字段,插入name字段的权限
grant select (name,age),update (name,age),insert(name) on syd.syd to syd;
--授权syd用户可以使用syd模式下的seq_id_seq序列
grant select,update on sequence syd.seq_id_seq to syd;
--授权syd用户可以使用syd模式下的所有序列
grant select,update on all sequences in schema syd to syd;
--授权默认表权限
alter default privileges in schema syd grant select,insert,update,delete on tables to syd
--授权默认自增序列权限
alter default privileges in schema syd grant select,update on sequences to syd;
--回收cc用户连接数据库syd的权限
revoke connect on database syd from cc;
--回收cc访问syd模式的权限
revoke usage on schema syd from cc;
--回收cc用户的syd权限
revoke syd from cc;
--回收syd用户可以访问syd模式下的syd表的权限
revoke select,insert,update,delete on syd.syd from syd;
--回收syd用户可以访问syd模式下的所有表的权限
revoke select,insert,update,delete on all tables in schema syd from syd;
--回收syd用户可以更新syd模式下的syd表的name列的权限
revoke update (name) on syd.syd from syd;
--回收syd用户对syd模式下的syd表,查看更新name、age字段,插入name字段的权限
revoke select (name,age),update (name,age),insert(name) on syd.syd from syd;
--回收syd用户可以使用syd模式下的seq_id_seq序列的权限
revoke select,update on sequence syd.seq_id_seq from syd;
--回收syd用户可以使用syd模式下的所有序列的权限
revoke select,update on all sequences in schema syd from syd;
--回收默认表权限
alter default privileges in schema syd revoke select,insert,update,delete on tables from syd
--回收默认自增序列权限
alter default privileges in schema syd revoke select,update on sequences from syd;