Here’s a quick guide to basic navigation inside a PostgreSQL database using the command-line interface (CLI).
- Access PostgreSQL To start using PostgreSQL, open a terminal and enter:
psql -U your_username -d your_databaseReplace your_username with your PostgreSQL username and your_database with the name of the database you want to access.
If you're connecting as the default PostgreSQL user (postgres), use:
psql -U postgresIf PostgreSQL requires a password, enter it when prompted.
- List Databases Once inside the PostgreSQL shell, list all databases with:
\lor:
\list- Switch to a Different Database To connect to another database:
\c database_nameor:
\connect database_name- List Tables in the Current Database To see all tables in the database:
\dtFor more details about tables:
\dt+- Describe a Table Structure To see the structure of a specific table:
\d table_nameFor extended details:
\d+ table_name- List Schemas To view all schemas in the database:
\dn- List Users (Roles) To see all users (roles) in the PostgreSQL instance:
\du- Run a Query Execute SQL commands, such as selecting all rows from a table:
SELECT * FROM table_name;- Exit the PostgreSQL Shell To leave the psql prompt, type:
\q