Site cover image

Site icon imagemy-site-blog

Description is here. The icon, the title, the description can be modified in Notion.

postgres操作コマンドまとめ

PostgreSQLでデータベース操作する際によく使用するコマンドをまとめます

ターミナル起動: psql

# デフォルトのデータベースに接続
psql

# データベースを指定して接続
psql -d <db_name>
psql -d postgres

# データベースとユーザを指定して接続
psql -d データベース名 -U ユーザ名
psql -d postgres -U user

データベース一覧取得 \l

postgres=# \l

List of databases
Name    | Owner | Encoding | Locale Provider |  Collate   |   Ctype    | ICU Locale | ICU Rules | Access privileges
-----------+-------+----------+-----------------+------------+------------+------------+-----------+-------------------
postgres  | user  | UTF8     | libc            | en_US.utf8 | en_US.utf8 |            |           |
template0 | user  | UTF8     | libc            | en_US.utf8 | en_US.utf8 |            |           | =c/user          +
|       |          |                 |            |            |            |           | user=CTc/user
template1 | user  | UTF8     | libc            | en_US.utf8 | en_US.utf8 |            |           | =c/user          +
|       |          |                 |            |            |            |           | user=CTc/user

データベースを切り替える: \c データベース名

postgres=# \c hoge
You are now connected to database "hoge" as user "user"

テーブルを表示: \dt

ivr=# \d
                List of relations
 Schema |        Name         |   Type   | Owner
--------+---------------------+----------+-------
 public | Customers           | table    | user
 public | Customers_id_seq    | sequence | user
 public | Inquiries           | table    | user
 public | Inquiries_id_seq    | sequence | user
 public | PhoneNumbers        | table    | user
 public | PhoneNumbers_id_seq | sequence | user
 public | Tenants             | table    | user
 public | Tenants_id_seq      | sequence | user
 public | Users               | table    | user
 public | Users_id_seq        | sequence | user
 public | WebhookLogs         | table    | user
 public | WebhookLogs_id_seq  | sequence | user