Sub topic 12
Exploring with psql meta-commands
In the earlier chapters you ran SQL in psql and used \c, \dt, \d books, and \q without much explanation. This chapter explains how those commands work, shows the ones you will use most, and covers the mistakes people commonly make with them.
It assumes you can start psql and connect to firstdb. You should also have the books table from the previous chapters.
What a meta-command is
A meta-command is an instruction to psql, the client program. It is not an instruction to the PostgreSQL server. Every meta-command starts with a backslash. SQL statements go to the server, but psql handles meta-commands itself. Many of them send queries to the server on your behalf and format the results.
This split explains most of the behavior you will see:
- A meta-command ends at the end of the line. It needs no semicolon.
- SQL can span many lines and ends at a semicolon.
- Meta-commands exist only in psql. Other tools, such as application drivers, do not understand them.
Connection and session commands
These commands tell you where you are and let you move.
\conninfo
\c postgres
\c firstdb
\q\conninfoprints the database, user, host, and port of the current connection. Use it when you are not sure which server you reached.\c nameconnects to another database. psql closes the current connection and opens a new one. It reportsYou are now connected to database "firstdb" as user "postgres".\qquits psql. Ctrl+D does the same on an empty line.
Listing databases
\l\l lists every database in the cluster, with owner, encoding, and access privileges. You will see postgres, template0, template1, and firstdb. The two template databases are patterns that CREATE DATABASE copies from. Do not modify them while you are learning.
\l+ adds database sizes and tablespaces.
Listing and describing objects
The \d family covers most exploring. The letter after \d selects the kind of object.
| Command | Lists |
|---|---|
| `\dt` | Tables |
| `\dv` | Views |
| `\di` | Indexes |
| `\ds` | Sequences |
| `\dn` | Schemas |
| `\du` | Roles (users and groups) |
| `\df` | Functions |
| `\dT` | Data types |
| `\dx` | Installed extensions |
Without arguments, \d lists tables, views, sequences, and similar relations. With a name, it describes that object:
\d booksThe output looks like this on a recent PostgreSQL version:
Table "public.books"
Column | Type | Collation | Nullable | Default
----------------+---------+-----------+----------+------------------------------
id | integer | | not null | generated always as identity
title | text | | not null |
author | text | | not null |
published_year | integer | | |
Indexes:
"books_pkey" PRIMARY KEY, btree (id)Read it against your CREATE TABLE statement:
Nullableshowsnot nullforid,title, andauthor.published_yearaccepts missing values.Defaultshows thatidis generated by the identity feature.Indexesshowsbooks_pkey. PostgreSQL created this index automatically to enforce the primary key.
The plus modifier
Adding + to a command shows more detail. \dt+ adds size and description columns. \d+ books adds storage settings and column descriptions.
\dt+
\d+ booksPatterns and schemas
Most \d commands accept a pattern. * matches any characters and ? matches one character.
\dt b*
\dt public.*
\dt *.*\dt shows only tables in schemas on your search path, and public is normally one of them. To include system tables, use \dt *.* or \dtS. The S modifier adds system objects.
Pattern matching also folds case. \d Books is treated as books. If a table was created with a quoted mixed-case name such as "Books", quote it in the pattern too: \d "Books".
Seeing what psql sends to the server
The \d commands are queries against system catalogs such as pg_class and pg_attribute. To see the SQL, start psql with -E:
psql -E -h localhost -U postgres -d firstdbYou can also turn it on inside a session:
\set ECHO_HIDDEN on
\d bookspsql then prints each hidden query before its result. This is a good way to learn the catalogs. It also shows you how to write the same lookup in SQL, which you need if you are working from a driver or script that has no meta-commands.
Display and timing settings
These commands change how results appear or add information.
\x
\timing
\pset null '(null)'
\pset pager off\xtoggles expanded display. Each row is printed as a vertical list of column and value pairs. This helps with wide tables.\x autoswitches to expanded display only when a result is too wide for the screen.\timingtoggles a line after each statement showing how long it took, in milliseconds.\pset null '(null)'prints missing values as(null)instead of blank. Blanks are easy to confuse with empty strings.\pset pager offstops psql from sending long output through a pager such asless. If you do land in a pager, pressqto leave it.
Try the expanded view on your data:
\x on
SELECT * FROM books WHERE title = 'Dune';
\x offGetting help and reusing work
\?
\h
\h CREATE TABLE\?lists all meta-commands.\hlists SQL commands.\hfollowed by a command name shows its syntax. This reflects the version of psql you run, so it matches what that client supports.
Other commands help you work with files and the query buffer:
| Command | What it does |
|---|---|
| `\e` | Opens the last query in your editor, then runs it when you save and exit |
| `\i file.sql` | Runs the SQL commands in a file |
| `\o file.txt` | Sends query output to a file. Use `\o` alone to go back to the screen |
| `\echo text` | Prints text, useful in scripts |
| `\watch 5` | Re-runs the last query every 5 seconds |
For example, save the statements from the earlier chapters in setup.sql and run them again with \i setup.sql. The path is relative to the directory where you started psql.
Common mistakes
- Adding a semicolon.
\dt;often appears to work, but psql passes the rest of the line to the command as arguments, so a semicolon can become part of a name. Write\c firstdb, not\c firstdb;. - Typing a meta-command inside a multi-line SQL statement. If the prompt changed to
firstdb-#, psql is still waiting for the end of a statement. Finish it with a semicolon, or press Ctrl+C to clear the buffer. - Reading an empty
\dtas "no tables." You may be connected to the wrong database. Run\conninfo. The messageDid not find any relations.means nothing matched in the visible schemas. - Using meta-commands in application code or a script run by another tool. The server rejects them with a syntax error. Use SQL against the catalogs, such as
information_schema.tables. - Forgetting that
\cstarts a new session. Settings like\xstay, because they belong to psql. But session-level server settings and temporary tables are lost.
Putting it together
This sequence uses the commands from this chapter to inspect your practice database:
\conninfo
\l
\dt+
\d+ books
\x on
SELECT * FROM books;
\x offYou should see the connection details, the list of databases, the size of books, its column definitions, and the data in expanded form.
Exercise
You run \dt in psql and see "Did not find any relations," but you are sure you created the books table. Name two meta-commands you would run to find the cause, and say what each tells you.
Show answer
Run \conninfo to see which database, user, host, and port you are connected to. You may be in postgres rather than firstdb. Run \l to confirm firstdb exists, then \c firstdb to switch to it. You can also run \dt *.* or \dn to check whether the table is in a schema that is not on your search path.
Exercise
How can you see the SQL that \d books sends to the server, and why is this useful?
Show answer
Start psql with -E, or run \set ECHO_HIDDEN on inside a session, then run \d books. psql prints each hidden query before its result. This is useful because it shows how to look up the same information in SQL, which you need where meta-commands are not available, such as in application code.