To interact with a PostgreSQL database, you typically use the
psql command-line interface if you are working directly from the terminal or command prompt. Here are the basic commands you’ll need for listing databases, selecting a database to use, and querying tables within that database:
- List all databases: To see all the databases in PostgreSQL, you use the command:
This command displays the list of databases along with other information like the database owner, encoding, and access privileges.
- Use (or switch to) a specific database: To select a database to work with, you use the
\ccommand followed by the name of the database. For example, if your database name is
exampledb, you would use:
This command connects you to the
exampledb database, allowing you to execute queries against it.
- Query tables within the selected database:
- List all tables: Once you’ve switched to your database, to see all the tables within that database, use the command:
\dtThis lists all the tables in the current database schema. If you want to see tables from all schemas, you can use:
- Querying data from a table: To query data from a specific table, you use the standard SQL
SELECTstatement. For example, if you want to select all columns from a table named
employees, you would use:
SELECT * FROM employees;
- Describing a table structure: To get detailed information about the columns of a table, you can use the
\dcommand followed by the name of the table. For example:
\d employeesThis command shows the column names, data types, and other information about the
These are the basic commands to get started with managing and querying databases and tables in PostgreSQL. Remember, to use these commands, you need to have access to the PostgreSQL server and appropriate permissions to view and query the databases and tables.