- 登入 psql 操作介面:
#su - postgres
$psql
#postgres=
- 連結 student 資料庫:
postgres=# \c student
已經連線到資料庫 "student",使用者 "postgres"。
- 查詢資料庫內的資料表:
student=# \d
relation 清單
架構模式 | 名稱 | 型別 | 擁有者
----------+----------+-------+----------
public | baselist | table | postgres
(1 筆資料列)
- 查詢資料表 baselist 的欄位:
student=# \d baselist
資料表 "public.baselist"
欄位 | 型別 | 修飾詞
---------+------------------------+---------
id | character varying(12) | 非 Null
name | character varying(50) | 非 Null
phones | character varying(11) | 非 Null
address | character varying(200) | 非 Null
索引:
"baselist_pkey" PRIMARY KEY, btree (id)
-
新增欄位 age ,並且加入限制 0~200 條件:
student=# ALTER TABLE baselist ADD COLUMN age int CHECK (age >=0 AND age <= 200);
ALTER TABLE
- 查詢資料表 baselist 的欄位:
student=# \d baselist
資料表 "public.baselist"
欄位 | 型別 | 修飾詞
---------+------------------------+---------
id | character varying(12) | 非 Null
name | character varying(50) | 非 Null
phones | character varying(11) | 非 Null
address | character varying(200) | 非 Null
age | integer |
索引:
"baselist_pkey" PRIMARY KEY, btree (id)
檢查條件約束
"baselist_age_check" CHECK (age >= 0 AND age <= 200)
-
故意加入一個超出範圍值的資料:
student=# UPDATE baselist SET age=201 WHERE id='S0001';
錯誤: 關係 "baselist" 的新資料列違反檢查限制 "baselist_age_check"
詳細資料: Failing row contains (S0001, Peter, 0912345678, Hd. Rd., No. 4321, 201).
-
加入一個合理範圍值的資料:
student=# UPDATE baselist SET age=20 WHERE id='S0001';
UPDATE 1
student=# SELECT * FROM baselist WHERE id='S0001';
id | name | phones | address | age
-------+-------+------------+-------------------+-----
S0001 | Peter | 0912345678 | Hd. Rd., No. 4321 | 20
(1 筆資料列)
-
修改表格欄位名稱 age ,成為 era :
student=# ALTER TABLE baselist RENAME COLUMN age TO era;
ALTER TABLE
student=# \d baselist;
資料表 "public.baselist"
欄位 | 型別 | 修飾詞
---------+------------------------+---------
id | character varying(12) | 非 Null
name | character varying(50) | 非 Null
phones | character varying(11) | 非 Null
address | character varying(200) | 非 Null
era | integer |
索引:
"baselist_pkey" PRIMARY KEY, btree (id)
檢查條件約束
"baselist_age_check" CHECK (era >= 0 AND era <= 200)
-
刪除檢查限制:
student=# ALTER TABLE baselist DROP CONSTRAINT "baselist_age_check";
ALTER TABLE
-
刪除 baselist 表格內的 era 欄位:
student=# ALTER TABLE baselist DROP COLUMN era;
ALTER TABLE
-
查詢 baselist 表格內容:
student=# SELECT * FROM baselist;
id | name | phones | address
-------+---------+------------+-------------------
S0002 | Jupiter | 0987654321 | Rd. Le, No. 123
S0001 | Peter | 0912345678 | Hd. Rd., No. 4321
(2 筆資料列)
-
修改表格 baselist 名稱,成為 baseData 表格名稱:
student=# ALTER TABLE baselist RENAME TO baseData;
ALTER TABLE
student=# \d baseData
資料表 "public.basedata"
欄位 | 型別 | 修飾詞
---------+------------------------+---------
id | character varying(12) | 非 Null
name | character varying(50) | 非 Null
phones | character varying(11) | 非 Null
address | character varying(200) | 非 Null
索引:
"baselist_pkey" PRIMARY KEY, btree (id)