1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PostgreSQLの操作をまとめる

Posted at

PostgreSQL の基本操作まとめ

この記事では、PostgreSQL における基本的なデータベース接続とテーブル操作について解説します。


1. DB 接続

1.1 psql コマンドで接続

psql -U <ユーザー名> -d <データベース名>

例:

psql -U postgres -d mydatabase

1.2 ホスト・ポートを指定する場合

psql -U <ユーザー名> -h <ホスト名> -p <ポート番号> -d <データベース名>

例:

psql -U postgres -h localhost -p 5432 -d mydatabase

1.3 Docker で接続する場合

docker exec -it <コンテナ名> psql -U <ユーザー名> -d <データベース名>

例:

docker exec -it my_postgres_container psql -U postgres -d mydatabase

2. Table 操作

2.1 テーブル一覧表示

\dt

またはスキーマも含めて表示する場合:

\dt *.*

2.2 テーブルの中身を表示

SELECT * FROM <テーブル名>;

例:

SELECT * FROM users;

2.3 テーブルの作成

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

2.4 テーブルの削除

DROP TABLE <テーブル名>;

例:

DROP TABLE users;

2.5 テーブルの中身を削除

TRUNCATE TABLE <テーブル名>;

例:

TRUNCATE TABLE users;

また、外部キー制約がある場合は以下のように CASCADE をつけることで関連データも削除できます。

TRUNCATE TABLE <テーブル名> CASCADE;

まとめ

PostgreSQLの基本的な操作をまとめました

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?