postgresql:常用字段類型、建表、增刪改查、索引


PostgreSQL

  常用字段類型:

類型 存儲長度 描述
int2/smallint 2字節 小范圍整數
int4/integer 4字節 常用的整數
varchar(n) 變長 有長度限制
bool 1字節 true/false
timestamp 8字節 日期和時間(無時區)

 

 

 

 

 

 

 

 

主鍵:

  指的是一個列或多列的組合,其值能唯一地標識表中的每一行,通過它可強制表的實體完整性。主鍵主要是用與其他表的外鍵關聯,以及本記錄的修改與刪除。

建表:

create table stu_infolyd(

  stu_id int4 primary key,      //主鍵
  stu_name varchar(20),
  stu_age int2,
  health bool,
  signtime timestamp);

修改表名:

alter table stu_infolyd rename to stulyd;

增:

insert into stulyd (stu_id,stu_name,stu_age,health,signtime)
values(201973001,'張三',20,true,'2020-06-08 11:46:00');

insert into stulyd (stu_id,stu_name,stu_age,health,signtime)
values(201973002,'張三豐',21,true,'2020-06-08 11:48:00');

insert into stulyd (stu_id,stu_name,stu_age,health,signtime)
values(201973003,'Jack',21,true,'2020-06-08 11:51:00');

刪:

delete from stulyd where stu_name='Jack';

改:

update stulyd set stu_age=22 where stu_name='張三';

查:

select * from stulyd;

select stu_id,stu_name from stulyd where stu_age>21;

select * from stulyd order by signtime desc;

修改字段類型:

alter table stulyd alter column stu_name type varchar(10);

 

索引

  索引是加速搜索引擎檢索數據的一種特殊表查詢。簡單地說,索引是一個指向表中數據的指針。

  索引的目的在於提高數據庫的性能。在查詢時,若沒有提前的准備,系統將不得不逐行掃描整個表,以查找所有匹配的條目。如果表中有很多行,並且查詢僅僅返回幾行(可能是零或一行),這顯然是一種低效的方法。但是如果系統已被指示在相應的列上建立索引,則可以使用更有效的方法來定位匹配的行。(類似字典目錄)

創建索引

create index index_name on tbl_name;
//單列索引

create index index_name on tbl_name (col_name);

例:
create index index_id on stulyd (stu_id);
//組合索引

create index index_name on tbl_name (col1_name,col2_name);

例:
create index index_info on stulyd (stu_id,stu_name);
//唯一索引

create unique index index_name on tbl_name (col_name);

例:
create unique index unique_id on stulyd (stu_id);
//局部索引

create index index_name on tbl_name (col_name) where 條件;

create index index_name on tbl_name (col_name) (條件);

例:
create index index_name on stulyd (signtime) where signtime!=null;

create index index_name on stulyd (signtime) (signtime!=null);

刪除索引:

drop index index_name;

什么情況下要避免使用索引?

  索引不應該使用在較小的表上;(索引會增加數據庫系統的開銷)

  索引不應該使用在有頻繁的大批量的更新或插入操作的表上;(索引必須保持與數據表的同步)

  索引不應該使用在含有大量的 NULL 值的列上;(?排序規則:NULL值會被歸到一塊)

  索引不應該使用在頻繁操作的列上。(索引必須保持與數據表的同步)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM