[PostgreSQL14.2] スキーマの作成

スキーマ(Schema)とは、1つのデータベースの中に複数設定することができる名前空間

$ psql –version
$ sudo -u postgres psql
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
———–+———-+———-+———+———+———————–
postgres | postgres | UTF8 | C.UTF-8 | C.UTF-8 |
template0 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
testdb | postgres | UTF8 | C.UTF-8 | C.UTF-8 |
(4 rows)
# \c testdb
You are now connected to database “testdb” as user “postgres”.

postgres=# \dn
List of schemas
Name | Owner
——–+———-
public | postgres
(1 row)

postgres=# create schema bank1;
CREATE SCHEMA
postgres=# create schema bank2;
CREATE SCHEMA
postgres=# \dn
List of schemas
Name | Owner
——–+———-
bank1 | postgres
bank2 | postgres
public | postgres
(3 rows)

### 現在のスキーマ
postgres=# select current_schema();
current_schema
—————-
public
(1 row)

### スキーマの変更
postgres=# set search_path = bank1;
SET
postgres=# select current_schema();
current_schema
—————-
bank1
(1 row)

### スキーマを指定してテーブル作成
create table bank1.data (
id integer,
name varchar(256)
);

スキーマのテーブルができている
# \dt bank1.*
List of relations
Schema | Name | Type | Owner
——–+——+——-+———-
bank1 | data | table | postgres
(1 row)

PHPから接続する場合はスキーマ指定が必要
なるほど、スキーマの概念を理解した