PostgreSQL Select Database
Overview
In PostgreSQL, you need to connect to a specific database before you can perform operations on it. This chapter explains how to select and switch between databases.
Selecting Database When Connecting
Using psql
Connection String Format
Example:
Switching Databases
Using \c Command
In psql, use \c or \connect command to switch databases:
Switch Example
View Current Database
Using psql Commands
Output Example
List All Databases
Using psql Commands
Using SQL Query
Selecting Database in Applications
Python (psycopg2)
Node.js (pg)
Java (JDBC)
Important Notes
- Connection limitation: Each database connection can only access one database
- Switching overhead: Frequent database switching increases connection overhead
- Permission check: Switching databases requires CONNECT privilege on the target database
- Default database: If no database is specified, usually connects to a database with the same name as the user
Common Issues
Database Does Not Exist
Solution: Create the database first or connect to another existing database.
Insufficient Permissions
Solution: Use a user with permissions or grant CONNECT privilege.