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;