postgresql命令操做

1.鏈接數據庫
psql -h Server -p Port -U Username DatabaseName算法

2.建立數據庫
postgres=# create database testdb;sql

3.查看數據庫
postgres=# \l數據庫

4.刪除數據庫
postgres=# drop database testdb;ide

5.進入數據庫
postgres=# \c testdb;函數

6.列出當前庫全部表
testdb=# \dtpost

7.建立表
testdb=# create table account(
testdb(# user_id serial primary key,
testdb(# username varchar(50) unique not null,
testdb(# password varchar(50) not null);rest

create table products (
testdb(# product_no integer,
testdb(# name varchar(20),
testdb(# price numeric);postgresql

create table account (
username varchar(50) unique not null,
count integer);code

create table company(
ID int primary key not null,
name TEXT not null,
age int not null,
address char(50),
salary real
);對象

create table audit(
emp_id int not null,
entry_date text not null
);

8.刪除表
testdb=# drop table account;

9.建立模式
testdb=# CREATE SCHEMA myschema;

10.指定模式建立表
create table myschema.mytable(
user_id serial primary key,
username varchar(50) unique not null,
password varchar(50) not null);

11.刪除模式裏的對象
drop schema myschema CASCADE;

12.刪除模式
drop schema myschema

13.插入數據
testdb=# insert into products values (1, 'chiness', 9.99);

14.查詢數據
testdb=# select * from products;

15.更新數據
testdb=# update products set name = 'hyh' where product_no = 1;

16.刪除表數據
testdb=# delete from products where name = 'hyh'; 字符串必須單引號

17.order by 升序,降序排列
testdb=# select from products order by price asc;
testdb=# select
from products order by price desc;

18.order by 多列排序
select * from products order by price,product_no asc;

19.group by分組
testdb=# select name, sum(price) from products group by name;
按名字分組統計每一個名字下的價格總額

20.HAVING子句與GROUP BY子句組合使用,用於選擇函數結果知足某些條件的特定行
testdb=# select name from products group by name having name != 'hyh';

21.條件查詢
AND 條件
testdb=# select * from products where name = 'hyh' and price = 10;

OR 條件
testdb=# select * from products where name = 'hyh' or price = 10;

AND & OR 條件
testdb=# select * from products where name = 'hyh' and price = 10 or product_no = 2;

NOT 條件
testdb=# select from products where name is not null;
testdb=# select
from products where name not in ('hyh','chiness');

LIKE 條件
testdb=# select * from products where name like '%ch%';

IN 條件
testdb=# select * from products where price in (13,15);

NOT IN 條件
testdb=# select * from products where name not in ('hyh','chiness');

BETWEEN 條件
testdb=# select * from products where price between 10 and 15;

22.鏈接
內鏈接(INNER JOIN)
testdb=# select products.name,account.count from products inner join account on products.name = account.username;

左外鏈接(LEFT OUTER JOIN)
左外鏈接返回從「ON」條件中指定的左側表中的全部行,只返回知足條件的另外一個表中的行
testdb=# select products.name,account.username,account.count from products left outer join account on products.price = account.count;

右外鏈接(RIGHT OUTER JOIN)
右外鏈接返回從「ON」條件中指定的右側表中的全部行,只返回知足條件的另外一個表中的行
testdb=# select products.name,account.count from products right outer join account on products.name = account.username;

全鏈接(FULL OUTER JOIN)跨鏈接(CROSS JOIN)
全外鏈接從左表和右表中返回全部行。 它將NULL置於不知足鏈接條件的位置
testdb=# select products.name,account.count from products full outer join account on products.name = account.username;

23.建立函數
create or replace function totalRecords()
returns integer as $total$
declare
total integer;
begin
select count(*) into total from products;
return total;
end;
$total$ language plpgsql;

24.調用函數
select totalRecords();

25.觸發器

PostgreSQL觸發器是一組動做或數據庫回調函數,它們在指定的表上執行指定的數據庫事件(即,INSERT,UPDATE,DELETE或TRUNCATE語句)時自動運行。 觸發器用於驗證輸入數據,執行業務規則,保持審計跟蹤等
1.PostgreSQL在如下狀況下執行/調用觸發器:在嘗試操做以前(在檢查約束並嘗試INSERT, UPDATE或DELETE以前)。或者在操做完成後(在檢查約束而且INSERT,UPDATE或DELETE完成後)。或者不是操做(在視圖中INSERT,UPDATE或DELETE的狀況下)
2.對於操做修改的每一行,都會調用一個標記爲FOR EACH ROWS的觸發器。 另外一方面,標記爲FOR EACH STATEMENT的觸發器只對任何給定的操做執行一次,而無論它修改多少行。
3.您能夠爲同一事件定義同一類型的多個觸發器,但條件是按名稱按字母順序觸發。
4.當與它們相關聯的表被刪除時,觸發器被自動刪除

例子:
    建立兩個表
    create table company(
    ID int primary key not null,
    name TEXT not null,
    age int not null,
    address char(50),
    salary real
   );

create table audit(
    emp_id int not null,
    entry_date text not null
);

    建立函數
    create or replace function auditlogfunc() returns trigger as $example_table$
begin
    insert into audit(emp_id, entry_date) values (new.id,current_timestamp);
    return new;
end;
$example_table$ language plpgsql;

    建立觸發器
    create trigger example_trigger after insert on company
for each row execute procedure auditlogfunc();

    insert into company values(1,'小米科技',2,'北京清河',1234);
    #向company插入數據後,自動觸發向audit表插入數據

26.索引
索引是用於加速從數據庫檢索數據的特殊查找表。數據庫索引相似於書的索引(目錄)。 索引爲出如今索引列中的每一個值建立一個條目
數據庫索引的重要特色:
索引使用SELECT查詢和WHERE子句加速數據輸出,可是會減慢使用INSERT和UPDATE語句輸入的數據
您能夠在不影響數據的狀況下建立或刪除索引
能夠經過使用CREATE INDEX語句建立索引,指定建立索引的索引名稱和表或列名稱
還能夠建立一個惟一索引,相似於惟一約束,該索引防止列或列的組合上有一個索引重複的索引

索引類型PostgreSQL中有幾種索引類型,如B-tree,Hash,GiST,SP-GiST和GIN等。每種索引類型根據不一樣的查詢使用不一樣的算法。 默認狀況下,CREATE INDEX命令使用B樹索引

在products表name字段建立索引(單列索引)
create index products_index on products (name);

多列索引
create index account_index on account (username,count);

惟一索引,不容許表中出現重複的值
create unique index account_index on account (username);

刪除索引
drop index account_index;

如下狀況避免使用索引
應該避免在小表上使用索引。
不要爲具備頻繁,大批量更新或插入操做的表建立索引。
索引不該用於包含大量NULL值的列。
不要在常常操做(修改)的列上建立索引
  1. 查詢表結構
    \d products;

28.union子句
PostgreSQL UNION子句/運算符用於組合兩個或多個SELECT語句的結果,而不返回任何重複的行。
要使用UNION,每一個SELECT必須具備相同的列數,相同數量的列表達式,相同的數據類型,而且具備相同的順序,但不必定要相同

SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;

union all 子句
SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION ALL
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;

29.alter table
PostgreSQL ALTER TABLE命令用於添加,刪除或修改現有表中的列。您還可使用ALTER TABLE命令在現有表上添加和刪除各類約束

增長字段
alter table company add gender char(1);

刪除字段
alter table company drop gender;

30.截斷表 TRUNCATE TABLE
PostgreSQL TRUNCATE TABLE命令用於從現有表中刪除完整的數據。您也可使用DROP TABLE命令刪除完整的表,但會從數據庫中刪除完整的表結構,若是但願存儲某些數據,則須要從新建立此表。
它和在每一個表上使用DELETE語句具備相同的效果,但因爲實際上並不掃描表,因此它的速度更快。 此外,它會當即回收磁盤空間,而不須要後續的VACUUM操做。 這在大表上是最有用的

truncate table company;

31.事務
事務具備如下四個標準屬性,通常是由首字母縮寫詞ACID簡稱
原子性(Atomicity):確保工做單位內的全部操做成功完成; 不然事務將在故障點停止,之前的操做回滾到其之前的狀態
一致性(Consistency):確保數據庫在成功提交的事務時正確更改狀態
隔離性(Isolation):使事務可以獨立運做並相互透明
持久性(Durability):確保在系統發生故障的狀況下,提交的事務的結果或效果仍然存在

如下命令用於控制事務:
BEGIN TRANSACTION:開始事務
COMMIT:保存更改,或者您可使用END TRANSACTION命令
ROLLBACK:回滾更改

回滾事務
testdb=# begin;
BEGIN
testdb=# delete from account where count = 10;
DELETE 1
testdb=# rollback;
ROLLBACK

提交事務
testdb=# begin;
BEGIN
testdb=# delete from account where count = 10;
DELETE 1
testdb=# commit;
COMMIT
testdb=# select * from account;

32.鎖
鎖或獨佔鎖或寫鎖阻止用戶修改行或整個表。 在UPDATE和DELETE修改的行在事務的持續時間內被自動獨佔鎖定。 這將阻止其餘用戶更改行,直到事務被提交或回退。
用戶必須等待其餘用戶當他們都嘗試修改同一行時。 若是他們修改不一樣的行,不須要等待。 SELECT查詢沒必要等待。
數據庫自動執行鎖定。 然而,在某些狀況下,必須手動控制鎖定。 手動鎖定能夠經過使用LOCK命令完成。 它容許指定事務的鎖類型和範圍

testdb=# lock table account in access exclusive mode;

33.子查詢
子查詢或內部查詢或嵌套查詢是一個PostgreSQL查詢中的查詢,它能夠嵌入到WHERE子句中。子查詢用於返回將在主查詢中使用的數據做爲進一步限制要檢索的數據的條件。子查詢能夠與SELECT,INSERT,UPDATE和DELETE語句以及運算符(如=,<,>,>=,<=,IN等)一塊兒使用。
子查詢必須遵循如下規則:
1.子查詢必須括在括號中
2.子查詢在SELECT子句中只能有一列,除非主查詢中有多個列用於比較其所選列的子查 詢。ORDER BY不能用於子查詢,儘管主查詢可使用ORDER BY。 GROUP BY可 用於執行與 子查詢中的ORDER BY相同的功能。
3.返回多行的子查詢只能與多個值運算符一塊兒使用,例如:IN,EXISTS,NOT IN,ANY / SOME,ALL運算符。
4.BETWEEN運算符不能與子查詢一塊兒使用; 可是,BETWEEN能夠在子查詢中使用

select子查詢
select * from company where id in (select id from company where salary > 45000);

insert子查詢插入數據
insert into company_bkp
select * from company
where id in (select id from company);

update 子查詢修改數據
update company
set salary = salary * 0.50
where age in (select age from company_bkp where age >= 27);

delete子查詢刪除數據
delete from company
where age in (select age from company_bkp
where age > 27);

34.自增列
PostgreSQL具備數據類型smallserial,serial和bigserial; 這些不是真正的類型,而只是在建立惟一標識符列的標誌以方便使用。 這些相似於一些其餘數據庫支持的AUTO_INCREMENT屬性。
若是您但願某列具備惟一的約束或是主鍵,則必須使用其餘數據類型進行指定。
類型名稱serial用於建立整數列。 類型名稱bigserial建立一個bigint類型的列。 若是您指望在表的使用期限內使用超過2^31個標識符,則應使用bigserial。 類型名稱smallserial建立一個smallint列

create table company(
id serial primary key, # 自增id name text not null,
age int not null,
address char(50),
salary real);

35.受權
建立用戶
create user hyh with password '123456';

grant all on company to hyh; 給用戶hyh授予company表的全部權限

取消受權
revoke all on company from hyh;

刪除用戶
drop user hyh;

36.重啓psqlsystemctl restart postgresql-9.5.service

相關文章
相關標籤/搜索