PostgreSQL数据库入门,定期总结学习成果,特此记录
常用数据类型:
1. 数值型:
integer 存储整数 4字节 -2147483648 至 +2147483647
bigint 存储大范围整数 8字节 -9223372036854775808 至 9223372036854775807
numeric 用户指定的精度 变量 小数点前最多为131072个数字; 小数点后最多为16383个数字
real 变精度,不精确 4字节 6位十进制数字精度
double 变精度,不精确 8字节 15位十进制数字精度
serial 自动递增整数 4字节 1 至 2147483647
bigserial 大的自动递增整数 8字节 1 至 9223372036854775807
备注:numeric 不指定长度,可以保留的整数位和小数位很大;numeric(6,4)表示精度为6,标度为4,例如23.5141
2. 字符串型
varchar(size) 变长,size指要存储的字符数
char(size) 定长,不足补空白
text 变长,无长度限制
备注:varchar如果不指定长度,可以存储的最大长度为1GB
3. 日期/时间型
timestamp [ (p) ] [ without time zone ] 8字节 日期和时间(无时区)
timestamp [ (p) ] with time zone 8字节 日期和时间(有时区)
4. 布尔型
boolean 1字节 指定true/false两种状态
PostgreSQL基础语句:
创建数据库:create database db_name;
删除数据库:drop database da_name;
一、DDL语句(数据库模式定义语言)
1. 创建表语句
create table table_name(
col01_name data_type,
col02_name data_type,
col03_name data_type);
示例:
create table score(
stu_name varchar(40),
math_score int,
test_date date);
2. 删除表语句
drop table table_name;
示例:
drop table score;
3. 重命名表语句
alter table table_name1 rename to table_name2;
示例:
alter table score rename to stu_score;
4. 添加字段语句
alter table table_name add col_name type;
示例:
alter table score add chin_score int;
5. 删除字段语句
alter table table_name drop col_name;
示例:
alter table table_name drop chin_score;
6. 重命名字段语句
alter table table_name rename col_name1 to col_name2;
示例:
alter table score rename chin_score to chinese_score;
二、DML语句(数据操纵语言)
1. 插入语句
insert into table_name(col01_name,col02_name,col03_name) values(col01_value,col02_value,col03_value);
示例:
insert into score(stu_name,math_score,test_date) values('Jack',98,'2020-06-06');
insert into score(stu_name,math_score,test_date) values('Mike',85,'2020-06-05');
2. 更新语句
update teble_name set col01_name=col01_value;
update table_name set col02_name=col02_value where col01_name=col01_value;
示例:
update score set math_score=100;
update score set math_score=99 where stu_name='Jack';
3. 删除语句
delete from table_name;
delete from table_name where col01_name=col01_value;
示例:
delete from score;
delete from score where test_date='2020-06-06';
三、查询语句
1. 单表查询语句
select col01_name,col02_name,col03_name from table_name;
示例:
select stu_name,math_score,test_date from score;
2. 过滤条件
select * from table_name where col01_name=col01_vlaue;
示例:
select * from score where stu_name='Mike';
select col01_name from score where math_score>90;
3. 排序
select * from table_name order by col01_name;
select * from table_name order by col01_name asc;
select * from table_name order by col01_name desc;
示例:
select * from score order by math_score;
select * from score order by math_score asc;
select stu_name from score order by math_score desc;