Changes your psql session to a different PostgreSQL database, similar to MySQL’s USE command.
PostgreSQL treats databases as separate server-level objects; standard SQL has no USE command. Instead, psql offers the meta-command \c
(or \connect
) to switch databases within the same server connection.
Run \c target_db
(or \c target_db username
if you need a different role). The prompt changes to confirm the new database.
Add \c target_db
on its own line. Because \c
is a psql directive, the file must be executed with psql, not via a client library that only interprets SQL.
If you are outside psql, reconnect using your driver’s connection string: postgresql://user:pass@host:5432/target_db
. Switching requires a new connection.
1. Jumping between ecommerce_dev
and ecommerce_prod
during debugging.
2. Running maintenance tasks on a staging database without opening a new terminal.
3. Loading data into throw-away scratch databases for ad-hoc analysis.
• Use dedicated roles per environment (app_dev
, app_prod
) and pass the role to \c
.
• Keep automated scripts environment-specific; avoid mid-script switches to reduce risk.
• In CI pipelines, open a fresh connection rather than \c
to make logs clearer.
Run SELECT current_database();
or check the psql prompt, which shows dbname=>
.
No. \c
immediately closes the current connection, discarding any open transaction.
\c
preserve session settings?It does not. GUCs like search_path
revert to the defaults of the new database.
Most GUI tools offer a database drop-down or a reconnect button that issues a new connection behind the scenes.