In psql, you can enter the following two types of commands:
A meta-command is a command for the psql client, whereas SQL is sent to the database server. An example of a meta-command is \q, which tells the client to disconnect. All lines that begin with \ (backslash) as the first nonblank character are presumed to be meta-commands of some kind.
If it isn't a meta-command, it's SQL. We keep reading SQL until we find a semicolon, so we can spread SQL across many lines and format it any way we find convenient.
The help command is the only exception. We provide this for people who are completely lost, which is a good thought; so let's start from there ourselves.
There are two types of help commands, which are as follows:
- \?: This provides help on psql meta-commands
- \h: This provides help on specific SQL commands
Consider the following snippet as an example:
postgres=# \h DELETE
Command: DELETE
Description: delete rows of a table
Syntax:
[ WITH [ RECURSIVE ] with_query [, ...] ]
DELETE FROM [ ONLY ] table [ [ AS ] alias ]
[ USING usinglist ]
[ WHERE condition | WHERE CURRENT OF cursor_name ]
[ RETURNING * | output_expression [ AS output_name ] [,]]
I find this a great way to discover and remember options and syntax. You'll also appreciate having the ability to scroll back through the previous command history.
You'll get a lot of benefits from tab completion, which will fill in the next part of the syntax when you press the Tab key. This also works for object names, so you can type in just the first few letters and then press Tab; all the options will be displayed. Thus, you can type in just enough letters to make the object name unique, and then hit Tab to get the rest of the name.
One-line comments begin with two dashes, as follows:
-- This is a single-line comment
Multiline comments are similar to those in C and Java:
/*
* Multiline comment
*/
You'll probably agree that psql looks a little daunting at first, with strange backslash commands. I do hope you'll take a few moments to understand the interface and keep digging for more information. The psql tool is one of the most surprising parts of PostgreSQL, and it is incredibly useful for database administration tasks when used alongside other tools.