1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【PostgreSQL】よく使うコマンド一覧

1
Posted at

はじめに

個人的によく使うPostgreSQLのコマンド一覧をまとめる

ログインからデータベース作成まで

command
# ログイン
psql -U postgres

# パスワード入力(入力しても何も変化ないように見えるがEnter押せばログインできる)

# データベース一覧表
\l

# データベース作成
CREATE DATABASE staff;

# ログアウト
\q

# ログイン
psql -U postgres staff;

テーブル操作

# 作成
CREATE TABLE users (
id int,
name text,
age int,
height int,
PRIMARY KEY(id)
);

# 外部キー参照して作成
CREATE TABLE teams (
id SERIAL,
user_id int REFERENCES users(id)
);

# テーブル名変更
ALTER TABLE users RENAME TO characters;

# 主キー変更
ALTER TABLE users DROP PRIMARY KEY, ADD PRIMARY KEY (age);

レコード操作

command
# 追加
INSERT INTO users (id, name, age, height) VALUES (1, 'Taro', 12, 140);

# 表示
SELECT * FROM users;
SELECT name FROM users;
SELECT age FROM users WHERE id = 1;

# 更新
UPDATE users SET name = 'JIRO' WHERE id = 1;

# 削除
DELETE FROM users;
DELETE FROM users WHERE height = 180;

WHERE部分

command
# aかつb
SELECT * FROM users WHERE age = 12 AND height = 150;

# aまたはb
SELECT * FROM users WHERE age = 12 OR height = 150;

カラム(列)操作

command
# カラム名変更
ALTER TABLE users RENAME COLUMN height TO weight;

# カラム追加
ALTER TABLE users ADD COLUMN place text;

# カラムを削除
ALTER TABLE users DROP COLUMN age;

さいごに

よく使うように感じるコマンドをまとめた。
よく使うコマンドが増えたら更新する。

参考サイト

1
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?