PostgreSQL で「FATAL: database does not exist」で接続できない
接続先の DB が存在しないと出る。
DB 名の綴り違い・未作成に加え、DB 名を省くとユーザー名と同名の DB に繋ぎに行く既定挙動も原因。
createdb で作るか -d で既存 DB を指定する。
公開: 更新:
症状できない · exit 2
psql -U postgres -d myapp -f whichdb.sql psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: database "myapp" does not exist
解決後できた · exit 0
psql -U postgres -d myapp -f whichdb.sql current_database ------------------ myapp (1 row)
2026-10-05 に postgres:17(PostgreSQL 17.11) で実際に打って取った出力。検証環境の詳細
要約
FATAL: database "myapp" does not exist は、接続しようとした名前のデータベースが存在しないときに出る。
psql は DB 名を省略すると「接続ユーザーと同名の DB」へ繋ごうとするため、意図せずこのエラーになることも多い。
まず対象の DB が作られているかを確認する。
実行例
postgres:17 のサーバーで、未作成の myapp を -d に渡すと database "myapp" does not exist になり、-d を省いて app ロールで繋ぐとユーザー名と同じ app を探しに行って同じエラーになった。psql -l で一覧を確かめ、createdb で myapp を作った後は同じ接続が通る。
$ psql -U postgres -d myapp -f whichdb.sql
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: database "myapp" does not exist
$ echo $?
2$ psql -U app -f whichdb.sql
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: database "app" does not exist
$ echo $?
2$ psql -U postgres -l
List of databases
Name | Owner | Encoding | Locale Provider | Collate | Ctype | Locale | ICU Rules | Access privileges
-----------+----------+----------+-----------------+------------+------------+--------+-----------+-----------------------
postgres | postgres | UTF8 | libc | en_US.utf8 | en_US.utf8 | | |
template0 | postgres | UTF8 | libc | en_US.utf8 | en_US.utf8 | | | =c/postgres +
| | | | | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | libc | en_US.utf8 | en_US.utf8 | | | =c/postgres +
| | | | | | | | postgres=CTc/postgres
(3 rows)$ psql -U postgres -d postgres -f whichdb.sql
current_database
------------------
postgres
(1 row)$ createdb -U postgres myapp$ psql -U postgres -d myapp -f whichdb.sql
current_database
------------------
myapp
(1 row)
$ echo $?
0— 2026-10-05 時点の出力
検証環境PostgreSQL 17.11 / 2026-10-05 検証
- 検証日
- 実行環境
postgres:17Debian GNU/Linux 13 (trixie)- バージョン
- PostgreSQL 17.11
この記事の「実行例」は、上記の環境で実際にコマンドを実行して得られた出力をそのまま掲載しています。 再現手順はリポジトリの検証スクリプトとして管理し、定期的に再実行して出力を更新しています。
解決策
1. データベースを作成する
createdb myapppsql から作るなら次のようにする。
CREATE DATABASE myapp;2. 既存の DB を指定して接続する
psql -U postgres -d postgrespostgres は初期作成される管理用 DB。
まずここへ繋いで様子を見るとよい。
3. データベース一覧を確認する
psql -U postgres -l表示された一覧と綴りを突き合わせ、正しい名前を -d に渡す。
よくある原因
- 綴り違い・未作成: 指定した DB 名が実在しない。
- 既定の DB 名:
psql -U aliceはaliceという名前の DB を探しに行く。 - 初期化直後: クラスタは作ったが、目的の DB をまだ作っていない。