PostgreSQL list database and query tables

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:

  1. List all databases: To see all the databases in PostgreSQL, you use the command:
   \l

or

   \list

This command displays the list of databases along with other information like the database owner, encoding, and access privileges.

  1. Use (or switch to) a specific database: To select a database to work with, you use the \c command followed by the name of the database. For example, if your database name is exampledb, you would use:
   \c exampledb

This command connects you to the exampledb database, allowing you to execute queries against it.

  1. 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: \dt This lists all the tables in the current database schema. If you want to see tables from all schemas, you can use: \dt *.*
  • Querying data from a table: To query data from a specific table, you use the standard SQL SELECT statement. 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 \d command followed by the name of the table. For example: \d employees This command shows the column names, data types, and other information about the employees table.

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.

Leave a Comment

Scroll to Top