Switching Between Databases in PostgreSQL psql
In PostgreSQL's command-line interface psql, switching between databases is straightforward. The \c (or \connect) command allows you to change the active database within the same psql session. Here’s how to switch databases in PostgreSQL using psql.
1. Using the \c Command
The \c (or \connect) command is the primary way to switch databases in psql.
Syntax:
\c database_name [username] database_name: The name of the database you want to switch to. username (optional): Specifies the username if you want to connect with a different user.
Example Code:
-- Switch to a different database
\c new_database -- Connects to 'new_database' as the current user
-- Optionally, connect to a database with a specific user
\c new_database another_user -- Connects to 'new_database' as 'another_user'
Explanation:
2. Connecting to a Database with psql Command-Line Options
When initially starting psql, you can specify the database you want to connect to using the -d option.
Syntax:
psql -U username -d database_name -U username: Specifies the username to connect with. -d database_name: Specifies the database to connect to.
Example Code:
# Start psql and connect directly to 'new_database' as 'my_user'
psql -U my_user -d new_database
Explanation:
3. Connecting to a Database After Logging in as Superuser
If you’re already connected to a database as a superuser, you can switch to any other database with \c without having to exit psql.
Example Code:
-- Connect to another database as a superuser
\c target_database
Explanation:
Important Notes
All PostgreSQL Questions, Answers, and Code Snippets Collection.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4