LoginSignup
1
2

More than 1 year has passed since last update.

ガチ初心者向けPostgreSQL

Last updated at Posted at 2022-07-25

ガチ初心者向けPostgreSQL

GCP上で使った時に覚えたことを殴り書きします。
環境毎に異なると思うのでコンソール画面(コマンドが使える画面)までは頑張って行ってください。ちなみにGCPの場合Cloud Shellで

gcloud sql connect db-name --user=postgres

Linuxから起動する場合は

service postgresql start

停止する場合は

sudo service postgresql stop

起動した状態で下記コマンドでコンソールに入れます。

sudo -u postgres psql

コンソールから出るときは

\q

DBの取り扱い

postgres=> \l

で存在するDBを一覧表示する。
気を付けることはPostgresでは「1コネクション=1DB」ということ。コマンドを使ってDBを切り替えたりはできず、使用したいDBにコネクトしてからコマンドを使用する必要がある。

postgres=> \connect [db_name]

こんな感じで目的のDBへ再接続できる。

Table

作成

CREATE TABLE IF NOT EXISTS sample_table(
    x integer,
    y integer,
    z archer(20)
);

こんな感じで作る。

テーブルが出来てるか確認する。

postgres=> \dt
            List of relations
 Schema |     Name     | Type  |  Owner
--------+--------------+-------+----------
 public | sample_table | table | postgres

挿入

データを追加する。

postgres=> insert into sample_table values (1, 1, 'hello');

挿入できてるか確認する。

postgres=> select * from sample_table;
   x    |   y  | z
--------+------+-------
      1 |    1 | hello

User

User 追加

postgres=> CREATE USER user_name WITH PASSWORD 'aaa';

権限追加

スーパーユーザ権限を付与する場合

postgres=> ALTER USER user_name WITH SUPERUSER;

\dt でユーザ一覧と権限が見れる。

拡張機能のインストール

GCEの場合はファイルは既にインストール済みなので

postgres=> create extension postgis

でpostgisという拡張機能が使えるようになる。

Linuxの場合はターミナル上でファイルをインストールしておく必要がある。

sudo apt install postgis

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2