How to Switch Database in PostgreSQL Quickly and Easily
In PostgreSQL, you cannot switch databases within the same session using a command like
USE. Instead, you must connect to the desired database by starting a new session with psql -d database_name or use the \c database_name command inside the psql tool to switch databases.Syntax
To switch databases in PostgreSQL, use the following syntax inside the psql command-line interface:
\c database_name- Connects to the specified database.\c database_name username- Connects to the specified database as the given user.
Alternatively, from outside psql, start a new session with:
psql -d database_name- Connects directly to the specified database.
sql
\c database_name \c database_name username psql -d database_name
Example
This example shows how to switch from the current database to another database named mydb inside the psql tool.
sql
postgres=# \c mydb You are now connected to database "mydb" as user "postgres".
Output
You are now connected to database "mydb" as user "postgres".
Common Pitfalls
Unlike some other database systems, PostgreSQL does not support switching databases with a simple USE command inside a session. Trying USE database_name; will cause an error.
Also, you cannot switch databases if you are connected through an application that does not support reconnecting. You must close the current connection and open a new one to the target database.
sql
/* Wrong way - this will cause an error */ USE mydb; /* Right way inside psql */ \c mydb
Output
ERROR: syntax error at or near "USE"
LINE 1: USE mydb;
Quick Reference
| Command | Description |
|---|---|
| \c database_name | Switch to the specified database inside psql |
| \c database_name username | Switch to the specified database as a specific user |
| psql -d database_name | Start a new psql session connected to the specified database |
Key Takeaways
PostgreSQL does not support switching databases with a SQL command like USE.
Use \c database_name inside psql to switch databases in the same session.
Start a new psql session with psql -d database_name to connect directly to another database.
You must reconnect to switch databases in applications that do not support session switching.
Trying to use USE database_name; will cause a syntax error in PostgreSQL.