Finding Syntax of a PSQL command

Post date: Dec 03, 2014 8:6:3 PM

One of the most frequent question asked by Newbies that  what is the syntax of a command like create table, create index etc. It is easily available through online help. Here is how. 

[gpadmin@sachi scripts]$ psql --help

This is psql 8.2.15, the PostgreSQL interactive terminal (Greenplum version).

Usage:

  psql [OPTION]... [DBNAME [USERNAME]]

General options:

  -c, --command=COMMAND    run only single command (SQL or internal) and exit

  -d, --dbname=DBNAME      database name to connect to (default: "gpadmin")

  -f, --file=FILENAME      execute commands from file, then exit

  -l, --list               list available databases, then exit

  -v, --set=, --variable=NAME=VALUE

                           set psql variable NAME to VALUE

  -X, --no-psqlrc          do not read startup file (~/.psqlrc)

  -1 ("one"), --single-transaction

                           execute command file as a single transaction

  --help                   show this help, then exit

  --version                output version information, then exit

Input and output options:

  -a, --echo-all           echo all input from script

  -e, --echo-queries       echo commands sent to server

  -E, --echo-hidden        display queries that internal commands generate

  -L, --log-file=FILENAME  send session log to file

  -n, --no-readline        disable enhanced command line editing (readline)

  -o, --output=FILENAME    send query results to file (or |pipe)

  -q, --quiet              run quietly (no messages, only query output)

  -s, --single-step        single-step mode (confirm each query)

  -S, --single-line        single-line mode (end of line terminates SQL command)

Output format options:

  -A, --no-align           unaligned table output mode

  -F, --field-separator=STRING

                           set field separator (default: "|")

  -H, --html               HTML table output mode

  -P, --pset=VAR[=ARG]     set printing option VAR to ARG (see \pset command)

  -R, --record-separator=STRING

                           set record separator (default: newline)

  -t, --tuples-only        print rows only

  -T, --table-attr=TEXT    set HTML table tag attributes (e.g., width, border)

  -x, --expanded           turn on expanded table output

Connection options:

  -h, --host=HOSTNAME      database server host or socket directory (default: "local socket")

  -p, --port=PORT          database server port (default: "5432")

  -U, --username=USERNAME  database user name (default: "gpadmin")

  -w, --no-password        never prompt for password

  -W, --password           force password prompt (should happen automatically)

For more information, type "\?" (for internal commands) or "\help" (for SQL commands) from within psql, or consult the psql section in the PostgreSQL

documentation.

Report bugs to <pgsql-bugs@postgresql.org>.

or from the psql command prompt.

sachi=#  \?

General

  \copyright             show PostgreSQL usage and distribution terms

  \g [FILE] or ;         execute query (and send results to file or |pipe)

  \h [NAME]              help on syntax of SQL commands, * for all commands

  \q                     quit psql

Query Buffer

  \e [FILE]              edit the query buffer (or file) with external editor

  \ef [FUNCNAME]         edit function definition with external editor

  \p                     show the contents of the query buffer

  \r                     reset (clear) the query buffer

  \s [FILE]              display history or save it to file

  \w FILE                write query buffer to file

Input/Output

  \copy ...              perform SQL COPY with data stream to the client host

  \echo [STRING]         write string to standard output

  \i FILE                execute commands from file

  \o [FILE]              send all query results to file or |pipe

  \qecho [STRING]        write string to query output stream (see \o)

Informational

  (options: S = show system objects, + = additional detail)

  \d[S+]                 list tables, views, and sequences

  \d[S+]  NAME           describe table, view, sequence, or index

  \da[S]  [PATTERN]      list aggregates

  \db[+]  [PATTERN]      list tablespaces

  \dc[S]  [PATTERN]      list conversions

  \dC     [PATTERN]      list casts

  \dd[S]  [PATTERN]      show comments on objects

  \ddp    [PATTERN]      list default privileges

  \dD[S]  [PATTERN]      list domains

  \des[+] [PATTERN]      list foreign servers

  \deu[+] [PATTERN]      list user mappings

  \dew[+] [PATTERN]      list foreign-data wrappers

  \df[antw][S+] [PATRN]  list [only agg/normal/trigger/window] functions

  \dF[+]  [PATTERN]      list text search configurations

  \dFd[+] [PATTERN]      list text search dictionaries

  \dFp[+] [PATTERN]      list text search parsers

  \dFt[+] [PATTERN]      list text search templates

  \dg[+]  [PATTERN]      list roles (groups)

  \di[S+] [PATTERN]      list indexes

  \dl                    list large objects, same as \lo_list

  \dn[+]  [PATTERN]      list schemas

  \do[S]  [PATTERN]      list operators

  \dp     [PATTERN]      list table, view, and sequence access privileges

  \dr[S+] [PATTERN]      list foreign tables

  \drds [PATRN1 [PATRN2]] list per-database role settings

  \ds[S+] [PATTERN]      list sequences

  \dt[S+] [PATTERN]      list tables

  \dT[S+] [PATTERN]      list data types

  \du[+]  [PATTERN]      list roles (users)

  \dv[S+] [PATTERN]      list views

  \dx     [PATTERN]      list external tables

  \l[+]                  list all databases

  \z      [PATTERN]      same as \dp

Formatting

  \a                     toggle between unaligned and aligned output mode

  \C [STRING]            set table title, or unset if none

  \f [STRING]            show or set field separator for unaligned query output

  \H                     toggle HTML output mode (currently off)

  \pset NAME [VALUE]     set table output option

                         (NAME := {format|border|expanded|fieldsep|footer|null|

                         numericlocale|recordsep|tuples_only|title|tableattr|pager})

  \t [on|off]            show only rows (currently off)

  \T [STRING]            set HTML <table> tag attributes, or unset if none

  \x [on|off]            toggle expanded output (currently off)

Connection

  \c[onnect] [DBNAME|- USER|- HOST|- PORT|-]

                         connect to new database (currently "sachi")

  \encoding [ENCODING]   show or set client encoding

  \password [USERNAME]   securely change the password for a user

  \conninfo              display information about current connection

Operating System

  \cd [DIR]              change the current working directory

  \timing [on|off]       toggle timing of commands (currently off)

  \! [COMMAND]           execute command in shell or start interactive shell

Variables

  \prompt [TEXT] NAME    prompt user to set internal variable

  \set [NAME [VALUE]]    set internal variable, or list all if no parameters

  \unset NAME            unset (delete) internal variable

Large Objects

  \lo_export LOBOID FILE

  \lo_import FILE [COMMENT]

  \lo_list

  \lo_unlink LOBOID      large object operations

sachi=# 

Finding SYNTAX for most commonly used command.

sachi=# \h create table

Command:     CREATE TABLE

Description: define a new table

Syntax:

CREATE [[GLOBAL | LOCAL] {TEMPORARY | TEMP}] TABLE table_name ( 

[ { column_name data_type [ DEFAULT default_expr ]     [column_constraint [ ... ]

[ ENCODING ( storage_directive [,...] ) ]

   | table_constraint

   | LIKE other_table [{INCLUDING | EXCLUDING} 

                      {DEFAULTS | CONSTRAINTS}] ...}

   [, ... ] ]

   [column_reference_storage_directive [, �] ]

   )

   [ INHERITS ( parent_table [, ... ] ) ]

   [ WITH ( storage_parameter=value [, ... ] )

   [ ON COMMIT {PRESERVE ROWS | DELETE ROWS | DROP} ]

   [ TABLESPACE tablespace ]

   [ DISTRIBUTED BY (column, [ ... ] ) | DISTRIBUTED RANDOMLY ]

   [ PARTITION BY partition_type (column)

       [ SUBPARTITION BY partition_type (column) ] 

          [ SUBPARTITION TEMPLATE ( template_spec ) ]

       [...]

    ( partition_spec ) 

        | [ SUBPARTITION BY partition_type (column) ]

          [...]

    ( partition_spec 

      [ ( subpartition_spec 

           [(...)] 

         ) ] 

    )

where storage_parameter is:

   APPENDONLY={TRUE|FALSE}

   BLOCKSIZE={8192-2097152}

   ORIENTATION={COLUMN|ROW}

   COMPRESSTYPE={ZLIB|QUICKLZ|RLE_TYPE|NONE}

   COMPRESSLEVEL={0-9}

   FILLFACTOR={10-100}

   OIDS[=TRUE|FALSE]

where column_constraint is:

   [CONSTRAINT constraint_name]

   NOT NULL | NULL 

   | UNIQUE [USING INDEX TABLESPACE tablespace]

            [WITH ( FILLFACTOR = value )]

   | PRIMARY KEY [USING INDEX TABLESPACE tablespace] 

                 [WITH ( FILLFACTOR = value )]

   | CHECK ( expression )

and table_constraint is:

   [CONSTRAINT constraint_name]

   UNIQUE ( column_name [, ... ] )

          [USING INDEX TABLESPACE tablespace] 

          [WITH ( FILLFACTOR=value )] 

   | PRIMARY KEY ( column_name [, ... ] ) 

                 [USING INDEX TABLESPACE tablespace] 

                 [WITH ( FILLFACTOR=value )] 

   | CHECK ( expression )

where partition_type is:

    LIST

  | RANGE

where partition_specification is:

partition_element [, ...]

and partition_element is:

   DEFAULT PARTITION name

  | [PARTITION name] VALUES (list_value [,...] )

  | [PARTITION name] 

     START ([datatype] 'start_value') [INCLUSIVE | EXCLUSIVE]

     [ END ([datatype] 'end_value') [INCLUSIVE | EXCLUSIVE] ]

     [ EVERY ([datatype] [number | INTERVAL] 'interval_value') ]

  | [PARTITION name] 

     END ([datatype] 'end_value') [INCLUSIVE | EXCLUSIVE]

     [ EVERY ([datatype] [number | INTERVAL] 'interval_value') ]

[ WITH ( partition_storage_parameter=value [, ... ] ) ]

[column_reference_storage_directive [, ...] ]

[ TABLESPACE tablespace ]

where subpartition_spec or template_spec is:

subpartition_element [, ...]

and subpartition_element is:

   DEFAULT SUBPARTITION name

  | [SUBPARTITION name] VALUES (list_value [,...] )

  | [SUBPARTITION name] 

     START ([datatype] 'start_value') [INCLUSIVE | EXCLUSIVE]

     [ END ([datatype] 'end_value') [INCLUSIVE | EXCLUSIVE] ]

     [ EVERY ([datatype] [number | INTERVAL] 'interval_value') ]

  | [SUBPARTITION name] 

     END ([datatype] 'end_value') [INCLUSIVE | EXCLUSIVE]

     [ EVERY ([datatype] [number | INTERVAL] 'interval_value') ]

[ WITH ( partition_storage_parameter=value [, ... ] ) ]

[column_reference_storage_directive [, ...] ]

[ TABLESPACE tablespace ]

where storage_directive is:

   COMPRESSTYPE={ZLIB | QUICKLZ | RLE_TYPE | NONE} 

 | COMPRESSLEVEL={0-9} 

 | BLOCKSIZE={8192-2097152}

Where column_reference_storage_directive is:

   COLUMN column_name ENCODING ( storage_directive [, ... ] ), ... 

 | DEFAULT COLUMN ENCODING ( storage_directive [, ... ] )

sachi=# \h analyze

Command:     ANALYZE

Description: collect statistics about a database

Syntax:

ANALYZE [ VERBOSE ] [ table [ (column [, ...] ) ] ]

[gpadmin@sachi scripts]$ \h create index

-bash: h: command not found

[gpadmin@sachi scripts]$ psql -d sachi

psql (8.2.15)

Type "help" for help.

sachi=# \h create index

Command:     CREATE INDEX

Description: define a new index

Syntax:

CREATE [UNIQUE] INDEX name ON table 

       [USING btree|bitmap|gist]

       ( {column | (expression)} [opclass] [, ...] )

       [ WITH ( FILLFACTOR = value ) ]

       [TABLESPACE tablespace]

       [WHERE predicate]