よく使用するPostgreSQLコマンド

ターミナル上でのコマンド

PostgreSQLを起動する

$ brew services start postgresql
==> Successfully started `postgresql` (label: homebrew.mxcl.postgresql)

PostgreSQLを停止する

$ brew services stop postgresql  
Stopping `postgresql`... (might take a while)
==> Successfully stopped `postgresql` (label: homebrew.mxcl.postgresql)

PostgreSQLの動作状況の確認

起動している場合

$ brew services list
Name       Status  User   Plist
postgresql started mimata /Users/xxx/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

起動していない場合

$ brew services list           
Name       Status  User Plist
postgresql stopped    

バージョン確認

$ psql -V
psql (PostgreSQL) 12.4

DB一覧を表示する

$ psql -l

               Name                | Owner  | Encoding | Collate | Ctype | Access privileges 
-----------------------------------+--------+----------+---------+-------+-------------------
 fake_insta_development            | xxx    | UTF8     | C       | C     | 
 fake_insta_test                   | xxx    | UTF8     | C       | C     | 
 partner_app_development           | xxx    | UTF8     | C       | C     | 
 partner_app_test                  | xxx    | UTF8     | C       | C     | 
 postgres                          | xxx    | UTF8     | C       | C     | 

DBにアクセスする

$ psql <DB名>

PostgreSQL内でのコマンド

コマンド一覧表示

\?

PostgreSQLを終了する

\q

DB一覧を表示する

\l

他のDBに接続する

\c <DB名>
You are now connected to database "DB名" as user "xxx".

DBを新規で作成する

create database <DB名>;

DBを削除する

drop database <DB名>;

テーブルを作成する

create table <テーブル名>
 (列名 データ型 制約,
 列名 データ型 制約, 
);

runteq_study=# create table "user"( # <= userはpsqlでは予約語なので使用するなら""で囲むこと!!
id serial not null,  # => mysql でのINT(11) AUTO_INCREMENTと等価
first_name varchar(30) not null,
last_name varchar(30) not null,
primary key (id));

参考

誰でも分かる!PostgreSQLでDB構築! - Qiita

テーブルの作成(CREATE TABLE) | PostgreSQLではじめるDB入門

テーブル一覧を表示する

\d

テーブルの詳細情報を確認する

\d TABLE NAME

テーブルを削除する

drop table <テーブル名>