Sub topic 3
Meta-commands and built-in help
This chapter assumes you can open a terminal and connect with psql, which the previous chapter covered. You should also know basic SQL and what a schema and a table are. Here you learn how psql separates its own commands from SQL, and how to find a command you have forgotten without leaving the prompt.
Two kinds of input
At the psql prompt you can type two different kinds of input.
- SQL statements are sent to the server. They end with a semicolon. The server parses and runs them.
- Meta-commands are handled by psql itself. They begin with a backslash, such as
\dtor\conninfo. The server never sees them.
Psql translates many meta-commands into ordinary catalog queries behind the scenes. For example, \dt runs a SELECT against pg_class and related catalogs. Because psql does the translation, meta-commands work only in psql. They do not work in pgAdmin's Query Tool, in application code, or in a driver such as psycopg.
The syntax of a meta-command
A meta-command is a backslash, a command name, and optional arguments separated by whitespace.
\d orders
\dt public.*
\c mydbFour rules explain most surprises.
- A meta-command ends at the end of the line. You do not type a semicolon. A trailing semicolon is usually passed as part of the argument and can cause an error or be ignored, depending on the command.
- You can put several on one line using
\\. This is rarely needed, but it is how you mix a meta-command with SQL in one line, such asSELECT 1 \g. - Arguments can be quoted. Single quotes group text that contains spaces, as in
\pset null '(null)'. - A meta-command cannot span lines. SQL can. Long SQL statements can run across many lines, but each meta-command must be complete on its own line.
You can type a meta-command while a SQL statement is half-written. Psql runs the meta-command and keeps the partial statement in its query buffer.
Getting help inside psql
Psql has three layers of help. Each answers a different question.
| Command | Answers the question | Example |
|---|---|---|
| `\?` | What meta-commands exist? | `\?` |
| `\h` or `\help` | What is the syntax of this SQL statement? | `\h CREATE INDEX` |
| `\conninfo` | Where am I connected right now? | `\conninfo` |
Help on meta-commands: `\?`
\? prints every meta-command with a one-line description. The list is long, so psql sends it through the pager (covered in a later chapter). Press q to leave the pager.
Newer versions of psql accept a topic after \?.
\? commands
\? options
\? variables\? commandslists the backslash commands. This is the same as plain\?.\? optionslists the command-line options, the same aspsql --help=options.\? variableslists the special psql variables, such asON_ERROR_STOP.
The variables help is useful later, when you customize psql.
Help on SQL: `\h`
\h with no argument lists every SQL command that psql has help for. With a command name it prints the syntax of that command.
\h
\h SELECT
\h CREATE TABLE
\h ALTER TABLEThe output comes from the psql client, not the server. It therefore describes the syntax for the psql version you are running. If your client is newer or older than your server, \h can show options your server does not support. When the two versions differ, check the documentation for the server version.
Multi-word commands work without quotes. Psql matches the longest command name it can, so \h CREATE INDEX finds the right entry. You can also use a wildcard to see a family of commands.
\h CREATE *Where am I: `\conninfo`
\conninfo prints the database, user, host and port of the current connection. Check it before you run anything that changes data. It tells you which server you are really talking to.
\conninfoTypical output looks like this, though the wording varies by version.
You are connected to database "mydb" as user "postgres" via socket in "/var/run/postgresql" at port "5432".If you see a socket path instead of a host name, you connected through a local Unix socket, not over TCP. That is the default when you omit -h.
Commands for working with the query buffer
Psql keeps the text of your current statement in a query buffer. Several meta-commands act on it. They help when a statement is long or has a typo.
| Command | What it does |
|---|---|
| `\p` | Prints the current query buffer. |
| `\r` | Resets (clears) the query buffer. |
| `\e` | Opens the buffer in your editor, then loads the result. |
| `\g` | Sends the buffer to the server. This is the same as typing a semicolon. |
| `\s` | Shows the command history. |
| `\q` | Quits psql. |
The pair \p and \r is the safest way to recover from a mistake. If you are unsure what is in the buffer, print it with \p. If it is wrong, clear it with \r.
\e uses the editor named by the PSQL_EDITOR, EDITOR or VISUAL environment variable. If none is set, psql falls back to a system default. When you save and close the editor, psql loads the text. In interactive mode it does not run the statement until you send it. Type ; or \g to run it.
A related command, \watch, repeats the buffer at an interval.
SELECT count(*) FROM pg_stat_activity;
\watch 5The \watch 5 runs the statement again every five seconds until you interrupt it with Ctrl+C. It is a quick way to observe a changing value.
Tab completion
Psql supports tab completion if it was built with the readline or libedit library. Most packages are. Press Tab once to complete a unique name and twice to list the options.
Completion works for:
- meta-command names, after typing a backslash;
- SQL keywords;
- table, column, schema and function names, using the current database.
Type \d then press Tab twice to see every \d variant. This is often faster than reading \?.
The `+` and `S` modifiers
Many \d commands accept two suffixes, which later chapters use heavily.
+asks for more detail.\d ordersshows columns and indexes.\d+ ordersalso shows storage settings, statistics targets and the table description.Sincludes system objects.\dthides tables inpg_catalogandinformation_schema.\dtSshows them.
You can combine them as in \dtS+.
A third argument is a pattern. Patterns use * to match any text and ? to match one character. Psql folds unquoted patterns to lower case, so \dt Orders looks for orders. Use double quotes to match a mixed-case name, as in \dt "Orders".
Common errors
invalid command \xyz: you mistyped a meta-command name. Use\?or Tab completion to check it.- Nothing happens after a SQL statement: you forgot the semicolon. The prompt changes from
mydb=#tomydb-#, which means psql is waiting for more input. Type;, or clear the buffer with\r. - A meta-command shows no objects: your pattern may not match the search path. Qualify the name, for example
\dt public.*. \hshows an option your server rejects: the client and server versions differ. CheckSELECT version();againstpsql --version.
Exercise
You type SELECT * FROM orders and press Enter. The prompt changes to mydb-# and nothing is returned. What is happening, and give two ways to get out of this state?
Show answer
The statement has no terminating semicolon, so psql treats it as unfinished and waits for more input. You can type ; (or \g) to run it, or type \r to clear the query buffer and start over.
Exercise
Which command shows the syntax of ALTER TABLE, and why might the output differ from what your server accepts?
Show answer
\h ALTER TABLE shows it. The text is built into the psql client, so it reflects the client's version. If the client and server versions differ, the syntax shown may include options the server does not support, or omit ones it does.
Exercise
What is the difference between \d orders and \d+ orders, and how would you include system tables when listing tables?
Show answer
\d+ orders adds extra detail, such as storage settings, statistics targets and the table description, to the output of \d orders. Adding S to a list command, as in \dtS, includes system tables.