info > psql(1)

Not found locally for psql. Try Google search

📖 NAME

🐘 psql - PostgreSQL interactive terminal

🚀 Quick Reference

Use CaseCommandDescription
🔗 Connect to a databasepsql -d dbnameConnect to a specific database, can also use psql dbname
⚡ Execute a single SQL commandpsql -c "SELECT * FROM table;"Run a command and exit
📄 Run commands from a filepsql -f filenameExecute SQL from a file
📋 List all databasespsql -lShow available databases and exit
📖 Get help on psql optionspsql --helpDisplay help about command-line options
🔍 Describe a table\d tablenameMeta-command to show table structure

📝 SYNOPSIS

psql [option...] [dbname [username]]

📖 DESCRIPTION

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.

âš™ī¸ OPTIONS

-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.

đŸšĒ Exit Codes

CodeMeaning
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

📚 USAGE

🔗 Connecting to a Database

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.

âŒ¨ī¸ Entering SQL Commands

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.

🔧 Meta-Commands

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:

🔍 Patterns

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.

🔧 Advanced Features

📝 Variables

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.

🔗 SQL Interpolation

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.

đŸ’Ŧ Prompting

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.

âŒ¨ī¸ Command-Line Editing

psql supports Readline for line editing and history. Tab-completion is available. To disable, add to ~/.inputrc:

$if psql
set disable-completion on
$endif

🌍 ENVIRONMENT

📁 FILES

📝 NOTES

đŸĒŸ NOTES FOR WINDOWS USERS

psql is a console application. Console windows use a different encoding. To change the code page:

  1. Set the code page: cmd.exe /c chcp 1252 (replace 1252 with your code page).
  2. Set the console font to Lucida Console.

💡 EXAMPLES

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)
psql(1)
📖 NAME 🚀 Quick Reference 📝 SYNOPSIS 📖 DESCRIPTION âš™ī¸ OPTIONS đŸšĒ Exit Codes 📚 USAGE
🔗 Connecting to a Database âŒ¨ī¸ Entering SQL Commands 🔧 Meta-Commands 🔍 Patterns 🔧 Advanced Features
🌍 ENVIRONMENT 📁 FILES 📝 NOTES đŸĒŸ NOTES FOR WINDOWS USERS 💡 EXAMPLES

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/)
Valid XHTML 1.0 Transitional!Valid CSS!