Not found locally for psql. Try Google search
đ psql - PostgreSQL interactive terminal
| Use Case | Command | Description |
|---|---|---|
| đ Connect to a database | psql -d dbname | Connect to a specific database, can also use psql dbname |
| ⥠Execute a single SQL command | psql -c "SELECT * FROM table;" | Run a command and exit |
| đ Run commands from a file | psql -f filename | Execute SQL from a file |
| đ List all databases | psql -l | Show available databases and exit |
| đ Get help on psql options | psql --help | Display help about command-line options |
| đ Describe a table | \d tablename | Meta-command to show table structure |
psql [option...] [dbname [username]]
psql is a terminal-based front-end to PostgreSQL. It enables you to type in queries interactively, issue them to PostgreSQL, and see the query results. Alternatively, input can be from a file or from command line arguments. In addition, psql provides a number of meta-commands and various shell-like features to facilitate writing scripts and automating a wide variety of tasks.
-a, --echo-all
đĸ Print all nonempty input lines to standard output as they are read. (This does not apply to lines read interactively.) Equivalent to setting ECHO to all.
-A, --no-align
đ Switches to unaligned output mode. Equivalent to \pset format unaligned.
-b, --echo-errors
â Print failed SQL commands to standard error output. Equivalent to setting ECHO to errors.
-c command, --command=command
đ¯ Execute the given command string. Can be repeated. If used, psql does not read from standard input. Each SQL command string is sent as a single request. To mix SQL and meta-commands, use repeated -c or pipe. Example: psql -c '\x' -c 'SELECT * FROM foo;'
--csv
đ Switches to CSV output mode. Equivalent to \pset format csv.
-d dbname, --dbname=dbname
đī¸ Specifies the database to connect to. Can be a connection string.
-e, --echo-queries
đ¤ Copy all SQL commands sent to the server to standard output. Equivalent to setting ECHO to queries.
-E, --echo-hidden
đ Echo the actual queries generated by \d and other backslash commands. Equivalent to setting ECHO_HIDDEN to on.
-f filename, --file=filename
đ Read commands from the file. Use - for standard input. Error messages include line numbers.
-F separator, --field-separator=separator
đ¤ Use separator as the field separator for unaligned output. Equivalent to \pset fieldsep.
-h hostname, --host=hostname
đĨī¸ Specifies the host name. If starts with slash, it's a Unix-domain socket directory.
-H, --html
đ Switches to HTML output mode. Equivalent to \pset format html.
-l, --list
đ List all available databases and exit. Connects to postgres unless specified otherwise.
-L filename, --log-file=filename
đ Write all query output to file in addition to normal output.
-n, --no-readline
đĢ Do not use Readline for line editing or history. Useful for cutting and pasting.
-o filename, --output=filename
đž Put all query output into file. Equivalent to \o.
-p port, --port=port
đ Specifies TCP port or local Unix-domain socket extension. Defaults to PGPORT or compiled default (5432).
-P assignment, --pset=assignment
âī¸ Specifies printing options, like -P format=latex.
-q, --quiet
đ¤Ģ Quiet mode: no welcome messages or informational output. Equivalent to setting QUIET to on.
-R separator, --record-separator=separator
đ Use separator as record separator for unaligned output. Equivalent to \pset recordsep.
-s, --single-step
đž Run in single-step mode: prompt before each command, with option to cancel.
-S, --single-line
âĄī¸ Single-line mode: newline terminates SQL command like a semicolon. Not encouraged.
-t, --tuples-only
đ Turn off column names and row count footer. Equivalent to \t or \pset tuples_only.
-T table_options, --table-attr=table_options
đ Specifies options to place within the HTML table tag.
-U username, --username=username
đ¤ Connect as the specified user.
-v assignment, --set=assignment, --variable=assignment
đ Perform variable assignment like \set. Use = to separate name and value.
-V, --version
âšī¸ Print psql version and exit.
-w, --no-password
đ Never issue a password prompt. Useful for batch jobs.
-W, --password
đ Force psql to prompt for a password before connecting.
-x, --expanded
đ Turn on expanded table formatting mode. Equivalent to \x.
-X, --no-psqlrc
đĢ Do not read the start-up file (psqlrc or ~/.psqlrc).
-z, --field-separator-zero
đ¤ Set field separator to zero byte. Equivalent to \pset fieldsep_zero.
-0, --record-separator-zero
đ¤ Set record separator to zero byte. Useful for xargs -0.
-1, --single-transaction
đ Wrap all -c/-f commands in a single transaction. Issues BEGIN/COMMIT.
-?, --help[=topic]
â Show help about psql and exit. Topics: options, commands, variables.
| Code | Meaning |
|---|---|
| 0 | â Normal completion |
| 1 | â Fatal error (e.g., out of memory, file not found) |
| 2 | â ī¸ Connection to server went bad (non-interactive session) |
| 3 | đ Error occurred in script and ON_ERROR_STOP was set |
psql is a regular PostgreSQL client. To connect, you need the target database name, host, port, and user. These can be specified via command-line options -d, -h, -p, -U, or via environment variables (PGDATABASE, PGHOST, PGPORT, PGUSER). You can also use a conninfo string or URI. Example:
$ psql "service=myservice sslmode=require"
$ psql postgresql://dbmaster:5433/mydb?sslmode=require
If the connection fails, psql returns an error and terminates. Client encoding is set to "auto" from locale settings.
In normal operation, psql provides a prompt (e.g., testdb=>). SQL commands are sent to the server when a semicolon is reached. Commands can span multiple lines. For security, if untrusted users have access, begin by removing publicly-writable schemas from search_path. psql also polls for asynchronous notification events (LISTEN/NOTIFY). C-style block comments are passed to the server; SQL-standard comments are removed by psql.
Any input beginning with an unquoted backslash is a psql meta-command. The format is \command [arguments]. Arguments can be quoted with single quotes; inside quotes, C-like substitutions (\n, \t, etc.) are applied. A colon (:) followed by a variable name is replaced by its value. Backquotes execute shell commands. SQL identifiers in arguments follow SQL syntax rules (lowercase unless double-quoted). Parsing stops at end of line or another unquoted backslash. The special sequence \\ marks end of arguments and continues SQL parsing.
Many meta-commands act on the current query buffer. The following meta-commands are defined:
\a â Switch between aligned and unaligned output format. (Backward compatibility)\c or \connect [-reuse-previous=on|off] [dbname [username [host [port]]] | conninfo]- to omit a parameter. The new connection can reuse parameters from the previous connection. Examples:=> \c mydb myuser host.dom 6432
=> \c service=foo
=> \c "host=localhost port=5432 dbname=mydb connect_timeout=10 sslmode=disable"
=> \c -reuse-previous=on sslmode=require
\C [title]\pset title.\cd [directory]\! pwd to print current directory.\conninfo\copy { table [ ( column_list ) ] } from { 'filename' | program 'command' | stdin | pstdin } [ [ with ] ( option [, ...] ) ] [ where condition ]\copy ... from stdin, data is read from the same source until \. or EOF. The entire remainder of the line is taken as arguments; no variable interpolation or backquote expansion.\copyright\crosstabview [colV [colH [colD [sortcolH]]]]colV becomes vertical header, colH horizontal header, colD the grid data. sortcolH can sort the horizontal header.\d[S+] [pattern]\d+ shows more details. Without pattern, equivalent to \dtvmsE.\da[S] [pattern]\dA[+] [pattern]\dAc[+] [access-method-pattern [input-type-pattern]]\dAf[+] [access-method-pattern [input-type-pattern]]\dAo[+] [access-method-pattern [operator-family-pattern]]\dAp[+] [access-method-pattern [operator-family-pattern]]\db[+] [pattern]\dc[S+] [pattern]\dC[+] [pattern]\dd[S] [pattern]\dD[S+] [pattern]\ddp [pattern]\dE[S+] [pattern], \di[S+] [pattern], \dm[S+] [pattern], \ds[S+] [pattern], \dt[S+] [pattern], \dv[S+] [pattern]\des[+] [pattern]\det[+] [pattern]\deu[+] [pattern]\deu+ may show remote user/password, be careful.\dew[+] [pattern]\df[anptwS+] [pattern [arg_pattern ...]]\dF[+] [pattern]\dFd[+] [pattern]\dFp[+] [pattern]\dFt[+] [pattern]\dg[S+] [pattern]\du).\dl\lo_list.\dL[S+] [pattern]\dn[S+] [pattern]\do[S+] [pattern [arg_pattern [arg_pattern]]]\dO[S+] [pattern]\dp [pattern]\dP[itn+] [pattern]\drds [role-pattern [database-pattern]]\dRp[+] [pattern]\dRs[+] [pattern]\dT[S+] [pattern]\du[S+] [pattern]\dx[+] [pattern]\dX [pattern]\dy[+] [pattern]\e or \edit [filename] [line_number]line_number positions cursor.\echo text [ ... ]-n as first argument to suppress trailing newline.\ef [function_description [line_number]]\encoding [encoding]\errverbose\ev [view_name [line_number]]\f [string]|.\g [ (option=value [...]) ] [filename]|command given, output is written there. If buffer empty, re-executes last query.\gdesc\gexec\gset [prefix]prefix is prepended to column names.\gx\g but forces expanded output mode.\h or \help [command]\h * shows help on all.\H or \html\i or \include filename- for standard input.\if expression, \elif expression, \else, \endif\elif, \else, or \endif.\ir or \include_relative filename\i but resolves relative file names relative to the current script's directory.\l[+] or \list[+] [pattern]+ shows sizes and descriptions.\lo_export loid filename\lo_import filename [comment]\lo_list\lo_unlink loid\o or \out [filename]\p or \print\password [username]\prompt [text] namename.\pset [option [value]]border, columns, csv_fieldsep, expanded, fieldsep, fieldsep_zero, footer, format, linestyle, null, numericlocale, pager, pager_min_lines, recordsep, recordsep_zero, tableattr, title, tuples_only, unicode_border_linestyle, unicode_column_linestyle, unicode_header_linestyle.\q or \quit\qecho text [ ... ]\echo but writes to query output channel.\r or \reset\restrict restrict_key\unrestrict is allowed.\s [filename]\set [name [value [ ... ]]]\unset.\setenv name [value]\sf[+] function_description+ numbers lines.\sv[+] view_name\t\T table_options\timing [on | off]\unrestrict restrict_key\unset name\w or \write filename\warn text [ ... ]\echo but writes to standard error.\watch [seconds]seconds (default 2) until interrupted.\x [on | off | auto]\z [pattern]\dp).\! [command]\? [topic]commands, options, variables.\;The \d commands accept a pattern parameter. Patterns are case-folded to lowercase unless double-quoted. * matches any sequence, ? matches any single character. A dot (.) separates schema and object name. Two dots separate database, schema, object. Regular expressions can be used (character classes, etc.) but . is a separator, * becomes .*, ? becomes .. If pattern is omitted, all visible objects in the current search path are shown.
psql provides variable substitution. Variables are name/value pairs. Set with \set, retrieve with : prefix. Example:
testdb=> \set foo bar
testdb=> \echo :foo
bar
Specially treated variables (all uppercase) control behavior. They cannot be unset; \unset sets them to default. Key variables: AUTOCOMMIT, DBNAME, ECHO, ECHO_HIDDEN, ENCODING, ERROR, FETCH_COUNT, HIDE_TABLEAM, HIDE_TOAST_COMPRESSION, HISTCONTROL, HISTFILE, HISTSIZE, HOST, IGNOREEOF, LASTOID, LAST_ERROR_MESSAGE, LAST_ERROR_SQLSTATE, ON_ERROR_ROLLBACK, ON_ERROR_STOP, PORT, PROMPT1, PROMPT2, PROMPT3, QUIET, ROW_COUNT, SERVER_VERSION_NAME, SERVER_VERSION_NUM, SHOW_CONTEXT, SINGLELINE, SINGLESTEP, SQLSTATE, USER, VERBOSITY, VERSION, VERSION_NAME, VERSION_NUM.
Variable values can be interpolated into SQL statements. Use :name for literal, :'name' for quoted literal, :"name" for quoted identifier. Example:
testdb=> \set foo 'my_table'
testdb=> SELECT * FROM :"foo";
Variable interpolation is not performed within quoted SQL literals. Use :\{?name\} to test if variable exists. Colon can be escaped with backslash.
Prompts can be customized using PROMPT1, PROMPT2, PROMPT3 variables. Escape sequences include %M (full host), %m (host truncated), %> (port), %n (user), %/ (database), %# (# for superuser, > otherwise), %R (prompt character), %x (transaction status), %l (line number). Use %[ ... %] for terminal control characters. Default prompts: '%/%R%x%# ' for 1 and 2, '>> ' for 3.
psql supports Readline for line editing and history. Tab-completion is available. To disable, add to ~/.inputrc:
$if psql
set disable-completion on
$endif
COLUMNS â Controls width for wrapped format and pager decision.PGDATABASE, PGHOST, PGPORT, PGUSER â Default connection parameters.PG_COLOR â Use color in diagnostic messages (always, auto, never).PSQL_EDITOR, EDITOR, VISUAL â Editor used by \e, \ef, \ev.PSQL_EDITOR_LINENUMBER_ARG â Argument to pass line number to editor.PSQL_HISTORY â Alternative location for command history file.PSQL_PAGER, PAGER â Pager program for output.PSQLRC â Alternative location for ~/.psqlrc.SHELL â Command executed by \!.TMPDIR â Directory for temporary files (default /tmp).psqlrc and ~/.psqlrc â System-wide and user startup files. Read after connection unless -X is used. Can be version-specific (e.g., ~/.psqlrc-9.2).~/.psql_history â Command history file (location can be overridden by HISTFILE or PSQL_HISTORY).-c implied -X; now it does not.psql is a console application. Console windows use a different encoding. To change the code page:
cmd.exe /c chcp 1252 (replace 1252 with your code page).Spread a command over multiple lines:
testdb=> CREATE TABLE my_table (
testdb(> first integer not null default 0,
testdb(> second text)
testdb-> ;
CREATE TABLE
Describe the table:
testdb=> \d my_table
Table "public.my_table"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+---------
first | integer | | not null | 0
second | text | | |
Change prompt:
testdb=> \set PROMPT1 '%n@%m %~%R%# '
peter@localhost testdb=>
Select data:
peter@localhost testdb=> SELECT * FROM my_table;
first | second
-------+--------
1 | one
2 | two
3 | three
4 | four
(4 rows)
Using \pset to change output format:
peter@localhost testdb=> \pset border 2
Border style is 2.
peter@localhost testdb=> SELECT * FROM my_table;
+-------+--------+
| first | second |
+-------+--------+
| 1 | one |
| 2 | two |
| 3 | three |
| 4 | four |
+-------+--------+
(4 rows)
Using short commands:
peter@localhost testdb=> \a \t \x
Output format is aligned.
Tuples only is off.
Expanded display is on.
peter@localhost testdb=> SELECT * FROM my_table;
-[ RECORD 1 ]-
first | 1
second | one
...
Using \g with formatting options:
peter@localhost testdb=> SELECT * FROM my_table
peter@localhost testdb-> \g (format=aligned tuples_only=off expanded=on)
-[ RECORD 1 ]-
first | 1
second | one
...
Using \df to find functions:
testdb=> \df int*pl * bigint
List of functions
Schema | Name | Result data type | Argument data types | Type
-----------+---------+------------------+---------------------+------
pg_catalog | int28pl | bigint | smallint, bigint | func
pg_catalog | int48pl | bigint | integer, bigint | func
pg_catalog | int8pl | bigint | bigint, bigint | func
(3 rows)
Using \crosstabview:
testdb=> SELECT first, second, first > 2 AS gt2 FROM my_table;
first | second | gt2
-------+--------+-----
1 | one | f
2 | two | f
3 | three | t
4 | four | t
(4 rows)
testdb=> \crosstabview first second
first | one | two | three | four
-------+-----+-----+-------+------
1 | f | | |
2 | | f | |
3 | | | t |
4 | | | | t
(4 rows)
Multiplication table with sorted columns:
testdb=> SELECT t1.first as "A", t2.first+100 AS "B", t1.first*(t2.first+100) as "AxB",
testdb(> row_number() over(order by t2.first) AS ord
testdb(> FROM my_table t1 CROSS JOIN my_table t2 ORDER BY 1 DESC
testdb(> \crosstabview "A" "B" "AxB" ord
A | 101 | 102 | 103 | 104
---+-----+-----+-----+-----
4 | 404 | 408 | 412 | 416
3 | 303 | 306 | 309 | 312
2 | 202 | 204 | 206 | 208
1 | 101 | 102 | 103 | 104
(4 rows)
Generated by phpman v4.10.0-7-g98e9fd5 Author: Che Dong Under GNU General Public License
2026-09-10 22:26 @2600:1f28:365:80b0:2634:f534:c836:dc5e
CrawledBy CCBot/2.0 (https://commoncrawl.org/faq/)