今まで適当にPostgreSQLを使ってきたので、学び直しの意味も兼ねて「完全攻略 PostgreSQL: 現場で使える最強データベース入門 」という書籍を読みました。
振り返りとして、自分なりにPostgreSQLの各種機能や使い方をまとめてみます。
作業リポジトリはこちら:
psqlコマンドライン操作の基礎
psqlコマンドの使い方
接続
- オプション
-
-hホスト名 -
-pポート番号 (default: 5432) -
-Uユーザー名 -
-d接続するデータベース名
-
PGPASSWORD=root1234 psql -U app -h ${PROJECT_NAME}-sample-postgresql -d sample -p 5432
スクリプト実行
SQLスクリプトファイルを実行します。
PGPASSWORD=root1234 psql -U app -h ${PROJECT_NAME}-sample-postgresql -d sample -p 5432 -f ${PROJECT_DIR}/docs/postgresql/resources/script.sql
環境変数を設定して接続
export PGUSER=app
export PGPASSWORD=root1234
export PGDATABASE=sample
export PGHOST=postgres-work-sample-postgresql
export PGPORT=5432
psql
.psqlrc で設定を自動的に読み込む
~/.psqlrc ファイルはpsql起動時に自動的に読み込まれる設定ファイルで、エイリアス設定や初期SQLの実行などが可能です。
~/.psqlrc
\set QUIET 1
\pset border 2
基本的なメタコマンド
※ メタコマンドの末尾に + をつけると詳細表示になる
- データベース・テーブル関連
-
\lデータベース一覧 -
\c データベース名データベースに接続 -
\dリレーション(テーブル、ビュー、シーケンス)の一覧を表示 -
\dtテーブル一覧を表示 -
\d テーブル名指定のテーブル構造(カラム、インデックスなど) を表示 -
\dp テーブル名指定のテーブルに対して誰にどんな権限が与えられているか
-
- ユーザー関連
-
\duユーザー一覧の表示
-
- スキーマ関連
-
\dnスキーマの一覧を表示 -
\dt+ スキーマ名.*スキーマに所属するテーブル一覧の表示
-
- 表示関連
-
\x [on|off|auto]拡張表示形式の切り替え -
timing実行時間表示のON/OFF -
\pset [設定項目 [値]]テーブルの出力オプション-
\pset format csv\pset border 2など
-
-
- ヘルプ関連
-
\?メタコマンド一覧表示 -
\h SQLコマンドSQL文法のヘルプ表示
-
- その他
-
qpsql の終了
-
コマンドの実行
\l
/*
List of databases
Name | Owner | Encoding | Locale Provider | Collate | Ctype | Locale | ICU Rules | Access privileges
-----------+-------+----------+-----------------+------------+------------+--------+-----------+-------------------
postgres | app | UTF8 | libc | en_US.utf8 | en_US.utf8 | | |
sample | app | UTF8 | libc | en_US.utf8 | en_US.utf8 | | |
template0 | app | UTF8 | libc | en_US.utf8 | en_US.utf8 | | | =c/app +
| | | | | | | | app=CTc/app
template1 | app | UTF8 | libc | en_US.utf8 | en_US.utf8 | | | =c/app +
| | | | | | | | app=CTc/app
(4 rows)
*/
\c sample
-- You are now connected to database "sample" as user "app".
\d
/*
List of relations
Schema | Name | Type | Owner
--------+--------------+----------+-------
public | users | table | app
public | users_id_seq | sequence | app
(2 rows)
*/
\dt
/*
List of tables
Schema | Name | Type | Owner
--------+-------+-------+-------
public | users | table | app
(1 row)
*/
\d users
/*
Table "public.users"
Column | Type | Collation | Nullable | Default
------------+-----------------------------+-----------+----------+-----------------------------------
id | integer | | not null | nextval('users_id_seq'::regclass)
name | character varying(100) | | |
email | character varying(255) | | |
created_at | timestamp without time zone | | | CURRENT_TIMESTAMP
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
"users_email_key" UNIQUE CONSTRAINT, btree (email)
*/
\dp users
/*
Access privileges
Schema | Name | Type | Access privileges | Column privileges | Policies
--------+-------+-------+-------------------+-------------------+----------
public | users | table | | |
(1 row)
*/
\du
/*
List of roles
Role name | Attributes
-----------+------------------------------------------------------------
app | Superuser, Create role, Create DB, Replication, Bypass RLS
*/
\dn
/*
List of schemas
Name | Owner
--------+-------------------
public | pg_database_owner
(1 row)
*/
--
\dt+ public.*
/*
List of tables
Schema | Name | Type | Owner | Persistence | Access method | Size | Description
--------+-------+-------+-------+-------------+---------------+------------+-------------
public | users | table | app | permanent | heap | 8192 bytes |
(1 row)
*/
\pset の設定値
\pset
/*
border 1
columns 0
csv_fieldsep ','
expanded off
fieldsep '|'
fieldsep_zero off
footer on
format aligned
linestyle ascii
null ''
numericlocale off
pager 1
pager_min_lines 0
recordsep '\n'
recordsep_zero off
tableattr
title
tuples_only off
unicode_border_linestyle single
unicode_column_linestyle single
unicode_header_linestyle single
xheader_width full
*/
縦表示に切り替え
\x on
-- Expanded display is on.
SELECT * FROM users;
/*
-[ RECORD 1 ]----------------------------
id | 1
name | keita midorikawa
email | keita.midorikawa@example.com
created_at | 2026-01-04 14:29:16.504546
-[ RECORD 2 ]----------------------------
id | 2
name | taro yamada
email | taro.yamada@example.com
created_at | 2026-01-04 14:29:16.504546
*/
CSV形式で出力
\x auto
-- Expanded display is used automatically.
\pset format -h
-- \pset: allowed formats are aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped0
\pset format csv
-- Output format is csv.
\pset format
-- Output format is csv.
SELECT * FROM users;
/*
id,name,email,created_at
1,keita midorikawa,keita.midorikawa@example.com,2026-01-04 14:29:16.504546
2,taro yamada,taro.yamada@example.com,2026-01-04 14:29:16.504546
*/
-- もとに戻す
\pset format aligned