Sub topic 12
Exploring with psql Meta-Commands
This chapter assumes that PostgreSQL is installed, the server is running, and you are connected to the firstdb database with psql. It also assumes that the books table from the previous chapter exists.
SQL and psql Commands
SQL is the language PostgreSQL uses to create, read, and change data. A psql meta-command is a command provided by the psql client itself. Meta-commands help you inspect your session and database. They start with a backslash (\) and do not use a semicolon.
For example, SELECT is SQL, while \dt is a psql meta-command:
SELECT title FROM books;
\dtThe semicolon ends the SQL statement. The \dt command runs as soon as you press Enter.
Listing Databases and Tables
Use \l to list the databases in the PostgreSQL cluster. A cluster is the PostgreSQL server installation that manages one or more databases.
Use \dt to list tables visible in the current database and schema:
\l
\dtThe \l output includes database names, owners, and connection settings. The \dt output usually includes the schema, table name, table type, and owner.
The current database matters. If \dt shows no tables, check that you are connected to the database where you created books.
Describing a Table
Use \d books to inspect the table definition:
\d booksThe output shows each column, its data type, whether it can contain NULL, and relevant defaults. It also shows indexes and constraints. The PRIMARY KEY constraint on id should appear in the output.
You can request more detail with \d+:
\d+ booksThe extended form can include storage information and the table's description. It is useful when investigating an unfamiliar table.
Leaving psql
Use \q to quit the psql client:
\qThis closes your client session. It does not stop the PostgreSQL server, delete a database, or change any table.
A Practical Inspection Sequence
When you begin work in a database, inspect it before changing data:
\l
\dt
\d booksThis sequence confirms which databases exist, which tables are visible, and how the selected table is defined. It can reveal that you are connected to the wrong database or that a table name is different from what you expected.
Exercise
Which command lists tables in the current database, and which command describes the columns and constraints of the books table?
Show answer
Use \dt to list tables and \d books to describe the books table.