Dragon Arrow written by Tatsuya Nakaji, all rights reserved animated-dragon-image-0164

postgreSQL コマンド

updated on 2019-03-08

イメージ

PostgreSQLコマンドチートシート


よく使うPostgreSQLで利用可能なコマンドのチートシートです。
環境:psql (PostgreSQL) 9.5.0

端末上で使うコマンド

サーバの起動

$ pg_ctl start -D /usr/local/var/postgres

サーバの終了

$ pg_ctl stop -D /usr/local/var/postgres

サーバが起動しているかの確認

$ ps aux | grep postgres

データベース接続

$ psql -d database -U user -h host

  • -d: データベース名(未指定だと、ログインユーザー名のデータベースに接続する)
  • -U: ユーザ名(未指定だと、ログインユーザー名になる)
  • -h: ホスト名(未指定だと、localhostになる)

データベース一覧表示

$ psql -l

PostgreSqlバージョン表示

$ psql -V

PostgreSqlに関するヘルプ

$ psql -help

psql上で使うコマンド

postgresの部分には接続中のDB名が入る。

psqlの終了

postgres=# ¥q

ユーザ一覧を表示

postgres=# \du

データベース一覧を表示

postgres=# \l

他のデータベースに接続

postgres=# \c dbname

データベース作成

postgres=# create database dbname;

接続中のデータベースの情報を表示

postgres=# \conninfo

テーブル一覧を表示

postgres=# \z

テーブル定義を確認

postgres=# \d tablename
tablenameには任意のテーブル名を入れる。

カレントディレクトリ変更

postgres=# \cd directory
カレントディレクトリをdirectoryに変更する。

CSV形式のファイルをテーブルに挿入

postgres=# \copy tablename from filename DELIMITER AS ','

ファイルからコマンドを実行

postgres=# \i filename.sql
ファイルから入力を読み取り、実行する。

コマンドラインの履歴の表示

postgres=# \s
\sの後にファイル名を入力すると、そのファイル名に結果を出力する。

'\'に関するヘルプの表示

postgres=# \?

シェル上のコマンドを使いたい場合

postgres=# \! command
commandの部分にlsやpwdを入れるとpsql上でもシェル上のコマンドが実行できる。