Postgresql Commands Cheat Sheet



PostgreSQL comes with a ton of configuration settings, but with documentationscattered all over The Manual!Here is a handy cheat sheet of all Postgres 10 configuration options, splitinto categories, with clickable links that go to the official documentation.Enjoy!

Postgresql Basic Commands Login to postgresql. Psql -U postgres psql -d mydb -U myuser -W psql -h myhost -d mydb -U myuser -W psql -U myuser -h myhost 'dbname=mydb. PostgreSQL Shell Cheat Sheet Starting the server. After you have run this command the first time, postgres will start automatically whenever you boot up your computer.

Autovacuum

autovacuumStarts the autovacuum subprocess.
autovacuum_analyze_scale_factorNumber of tuple inserts, updates, or deletes prior to analyze as a fraction of reltuples.
autovacuum_analyze_thresholdMinimum number of tuple inserts, updates, or deletes prior to analyze.
autovacuum_freeze_max_ageAge at which to autovacuum a table to prevent transaction ID wraparound.
autovacuum_max_workersSets the maximum number of simultaneously running autovacuum worker processes.
autovacuum_multixact_freeze_max_ageMultixact age at which to autovacuum a table to prevent multixact wraparound.
autovacuum_naptimeTime to sleep between autovacuum runs.
autovacuum_vacuum_cost_delayVacuum cost delay in milliseconds, for autovacuum.
autovacuum_vacuum_cost_limitVacuum cost amount available before napping, for autovacuum.
autovacuum_vacuum_scale_factorNumber of tuple updates or deletes prior to vacuum as a fraction of reltuples.
autovacuum_vacuum_thresholdMinimum number of tuple updates or deletes prior to vacuum.

Client Connection Defaults / Locale and Formatting

client_encodingSets the client’s character set encoding.
DateStyleSets the display format for date and time values.
default_text_search_configSets default text search configuration.
extra_float_digitsSets the number of digits displayed for floating-point values.
IntervalStyleSets the display format for interval values.
lc_collateShows the collation order locale.
lc_ctypeShows the character classification and case conversion locale.
lc_messagesSets the language in which messages are displayed.
lc_monetarySets the locale for formatting monetary amounts.
lc_numericSets the locale for formatting numbers.
lc_timeSets the locale for formatting date and time values.
server_encodingSets the server (database) character set encoding.
TimeZoneSets the time zone for displaying and interpreting time stamps.
timezone_abbreviationsSelects a file of time zone abbreviations.
Postgresql commands cheat sheet 2020

Client Connection Defaults / Other Defaults

dynamic_library_pathSets the path for dynamically loadable modules.
gin_fuzzy_search_limitSets the maximum allowed result for exact search by GIN.
tcp_keepalives_countMaximum number of TCP keepalive retransmits.
tcp_keepalives_idleTime between issuing TCP keepalives.
tcp_keepalives_intervalTime between TCP keepalive retransmits.

Client Connection Defaults / Shared Library Preloading

local_preload_librariesLists unprivileged shared libraries to preload into each backend.
session_preload_librariesLists shared libraries to preload into each backend.
shared_preload_librariesLists shared libraries to preload into server.

Client Connection Defaults / Statement Behavior

bytea_outputSets the output format for bytea.
check_function_bodiesCheck function bodies during CREATE FUNCTION.
default_tablespaceSets the default tablespace to create tables and indexes in.
default_transaction_deferrableSets the default deferrable status of new transactions.
default_transaction_isolationSets the transaction isolation level of each new transaction.
default_transaction_read_onlySets the default read-only status of new transactions.
gin_pending_list_limitSets the maximum size of the pending list for GIN index.
idle_in_transaction_session_timeoutSets the maximum allowed duration of any idling transaction.
lock_timeoutSets the maximum allowed duration of any wait for a lock.
search_pathSets the schema search order for names that are not schema-qualified.
session_replication_roleSets the session’s behavior for triggers and rewrite rules.
statement_timeoutSets the maximum allowed duration of any statement.
temp_tablespacesSets the tablespace(s) to use for temporary tables and sort files.
transaction_deferrableWhether to defer a read-only serializable transaction until it can be executed with no possible serialization failures.
transaction_isolationSets the current transaction’s isolation level.
transaction_read_onlySets the current transaction’s read-only status.
vacuum_freeze_min_ageMinimum age at which VACUUM should freeze a table row.
vacuum_freeze_table_ageAge at which VACUUM should scan whole table to freeze tuples.
vacuum_multixact_freeze_min_ageMinimum age at which VACUUM should freeze a MultiXactId in a table row.
vacuum_multixact_freeze_table_ageMultixact age at which VACUUM should scan whole table to freeze tuples.
xmlbinarySets how binary values are to be encoded in XML.
xmloptionSets whether XML data in implicit parsing and serialization operations is to be considered as documents or content fragments.

Connections and Authentication / Connection Settings

bonjourEnables advertising the server via Bonjour.
bonjour_nameSets the Bonjour service name.
listen_addressesSets the host name or IP address(es) to listen to.
max_connectionsSets the maximum number of concurrent connections.
portSets the TCP port the server listens on.
superuser_reserved_connectionsSets the number of connection slots reserved for superusers.
unix_socket_directoriesSets the directories where Unix-domain sockets will be created.
unix_socket_groupSets the owning group of the Unix-domain socket.
unix_socket_permissionsSets the access permissions of the Unix-domain socket.

Connections and Authentication / Security and Authentication

authentication_timeoutSets the maximum allowed time to complete client authentication.
db_user_namespaceEnables per-database user names.
krb_caseins_usersSets whether Kerberos and GSSAPI user names should be treated as case-insensitive.
krb_server_keyfileSets the location of the Kerberos server key file.
password_encryptionEncrypt passwords.
row_securityEnable row security.
sslEnables SSL connections.
ssl_ca_fileLocation of the SSL certificate authority file.
ssl_cert_fileLocation of the SSL server certificate file.
ssl_ciphersSets the list of allowed SSL ciphers.
ssl_crl_fileLocation of the SSL certificate revocation list file.
ssl_dh_params_fileLocation of the SSL DH parameters file.
ssl_ecdh_curveSets the curve to use for ECDH.
ssl_key_fileLocation of the SSL server private key file.
ssl_prefer_server_ciphersGive priority to server ciphersuite order.

Developer Options

allow_system_table_modsAllows modifications of the structure of system tables.
ignore_checksum_failureContinues processing after a checksum failure.
ignore_system_indexesDisables reading from system indexes.
post_auth_delayWaits N seconds on connection startup after authentication.
pre_auth_delayWaits N seconds on connection startup before authentication.
trace_notifyGenerates debugging output for LISTEN and NOTIFY.
trace_recovery_messagesEnables logging of recovery-related debugging information.
trace_sortEmit information about resource usage in sorting.
wal_consistency_checkingSets the WAL resource managers for which WAL consistency checks are done.
zero_damaged_pagesContinues processing past damaged page headers.

Error Handling

exit_on_errorTerminate session on any error.
restart_after_crashReinitialize server after backend crash.

File Locations

config_fileSets the server’s main configuration file.
data_directorySets the server’s data directory.
external_pid_fileWrites the postmaster PID to the specified file.
hba_fileSets the server’s “hba” configuration file.
ident_fileSets the server’s “ident” configuration file.

Lock Management

deadlock_timeoutSets the time to wait on a lock before checking for deadlock.
max_locks_per_transactionSets the maximum number of locks per transaction.
max_pred_locks_per_pageSets the maximum number of predicate-locked tuples per page.
max_pred_locks_per_relationSets the maximum number of predicate-locked pages and tuples per relation.
max_pred_locks_per_transactionSets the maximum number of predicate locks per transaction.

Preset Options

block_sizeShows the size of a disk block.
data_checksumsShows whether data checksums are turned on for this cluster.
debug_assertionsShows whether the running server has assertion checks enabled.
integer_datetimesDatetimes are integer based.
max_function_argsShows the maximum number of function arguments.
max_identifier_lengthShows the maximum identifier length.
max_index_keysShows the maximum number of index keys.
segment_sizeShows the number of pages per disk file.
server_versionShows the server version.
server_version_numShows the server version as an integer.
wal_block_sizeShows the block size in the write ahead log.
wal_segment_sizeShows the number of pages per write ahead log segment.

Process Title

cluster_nameSets the name of the cluster, which is included in the process title.
update_process_titleUpdates the process title to show the active SQL command.

Query Tuning / Genetic Query Optimizer

geqoEnables genetic query optimization.
geqo_effortGEQO: effort is used to set the default for other GEQO parameters.
geqo_generationsGEQO: number of iterations of the algorithm.
geqo_pool_sizeGEQO: number of individuals in the population.
geqo_seedGEQO: seed for random path selection.
geqo_selection_biasGEQO: selective pressure within the population.
geqo_thresholdSets the threshold of FROM items beyond which GEQO is used.

Query Tuning / Other Planner Options

constraint_exclusionEnables the planner to use constraints to optimize queries.
cursor_tuple_fractionSets the planner’s estimate of the fraction of a cursor’s rows that will be retrieved.
default_statistics_targetSets the default statistics target.
force_parallel_modeForces use of parallel query facilities.
from_collapse_limitSets the FROM-list size beyond which subqueries are not collapsed.
join_collapse_limitSets the FROM-list size beyond which JOIN constructs are not flattened.

Query Tuning / Planner Cost Constants

cpu_index_tuple_costSets the planner’s estimate of the cost of processing each index entry during an index scan.
cpu_operator_costSets the planner’s estimate of the cost of processing each operator or function call.
cpu_tuple_costSets the planner’s estimate of the cost of processing each tuple (row).
effective_cache_sizeSets the planner’s assumption about the size of the disk cache.
min_parallel_index_scan_sizeSets the minimum amount of index data for a parallel scan.
min_parallel_table_scan_sizeSets the minimum amount of table data for a parallel scan.
parallel_setup_costSets the planner’s estimate of the cost of starting up worker processes for parallel query.
parallel_tuple_costSets the planner’s estimate of the cost of passing each tuple (row) from worker to master backend.
random_page_costSets the planner’s estimate of the cost of a nonsequentially fetched disk page.
seq_page_costSets the planner’s estimate of the cost of a sequentially fetched disk page.

Query Tuning / Planner Method Configuration

enable_bitmapscanEnables the planner’s use of bitmap-scan plans.
enable_gathermergeEnables the planner’s use of gather merge plans.
enable_hashaggEnables the planner’s use of hashed aggregation plans.
enable_hashjoinEnables the planner’s use of hash join plans.
enable_indexonlyscanEnables the planner’s use of index-only-scan plans.
enable_indexscanEnables the planner’s use of index-scan plans.
enable_materialEnables the planner’s use of materialization.
enable_mergejoinEnables the planner’s use of merge join plans.
enable_nestloopEnables the planner’s use of nested-loop join plans.
enable_seqscanEnables the planner’s use of sequential-scan plans.
enable_sortEnables the planner’s use of explicit sort steps.
enable_tidscanEnables the planner’s use of TID scan plans.

Replication

track_commit_timestampCollects transaction commit time.

Replication / Master Server

synchronous_standby_namesNumber of synchronous standbys and list of names of potential synchronous ones.
vacuum_defer_cleanup_ageNumber of transactions by which VACUUM and HOT cleanup should be deferred, if any.

Replication / Sending Servers

max_replication_slotsSets the maximum number of simultaneously defined replication slots.
max_wal_sendersSets the maximum number of simultaneously running WAL sender processes.
wal_keep_segmentsSets the number of WAL files held for standby servers.
wal_sender_timeoutSets the maximum time to wait for WAL replication.

Replication / Standby Servers

hot_standbyAllows connections and queries during recovery.
hot_standby_feedbackAllows feedback from a hot standby to the primary that will avoid query conflicts.
max_standby_archive_delaySets the maximum delay before canceling queries when a hot standby server is processing archived WAL data.
max_standby_streaming_delaySets the maximum delay before canceling queries when a hot standby server is processing streamed WAL data.
wal_receiver_status_intervalSets the maximum interval between WAL receiver status reports to the primary.
wal_receiver_timeoutSets the maximum wait time to receive data from the primary.
wal_retrieve_retry_intervalSets the time to wait before retrying to retrieve WAL after a failed attempt.

Replication / Subscribers

max_logical_replication_workersMaximum number of logical replication worker processes.
max_sync_workers_per_subscriptionMaximum number of table synchronization workers per subscription.

Reporting and Logging / What to Log

application_nameSets the application name to be reported in statistics and logs.
debug_pretty_printIndents parse and plan tree displays.
debug_print_parseLogs each query’s parse tree.
debug_print_planLogs each query’s execution plan.
debug_print_rewrittenLogs each query’s rewritten parse tree.
log_autovacuum_min_durationSets the minimum execution time above which autovacuum actions will be logged.
log_checkpointsLogs each checkpoint.
log_connectionsLogs each successful connection.
log_disconnectionsLogs end of a session, including duration.
log_durationLogs the duration of each completed SQL statement.
log_error_verbositySets the verbosity of logged messages.
log_hostnameLogs the host name in the connection logs.
log_line_prefixControls information prefixed to each log line.
log_lock_waitsLogs long lock waits.
log_replication_commandsLogs each replication command.
log_statementSets the type of statements logged.
log_temp_filesLog the use of temporary files larger than this number of kilobytes.
log_timezoneSets the time zone to use in log messages.

Reporting and Logging / When to Log

client_min_messagesSets the message levels that are sent to the client.
log_min_duration_statementSets the minimum execution time above which statements will be logged.
log_min_error_statementCauses all statements generating error at or above this level to be logged.
log_min_messagesSets the message levels that are logged.

Reporting and Logging / Where to Log

event_sourceSets the application name used to identify PostgreSQL messages in the event log.
log_destinationSets the destination for server log output.
log_directorySets the destination directory for log files.
log_file_modeSets the file permissions for log files.
log_filenameSets the file name pattern for log files.
log_rotation_ageAutomatic log file rotation will occur after N minutes.
log_rotation_sizeAutomatic log file rotation will occur after N kilobytes.
log_truncate_on_rotationTruncate existing log files of same name during log rotation.
logging_collectorStart a subprocess to capture stderr output and/or csvlogs into log files.
syslog_facilitySets the syslog “facility” to be used when syslog enabled.
syslog_identSets the program name used to identify PostgreSQL messages in syslog.
syslog_sequence_numbersAdd sequence number to syslog messages to avoid duplicate suppression.
syslog_split_messagesSplit messages sent to syslog by lines and to fit into 1024 bytes.

Resource Usage / Asynchronous Behavior

backend_flush_afterNumber of pages after which previously performed writes are flushed to disk.
effective_io_concurrencyNumber of simultaneous requests that can be handled efficiently by the disk subsystem.
max_parallel_workersSets the maximum number of parallel workers than can be active at one time.
max_parallel_workers_per_gatherSets the maximum number of parallel processes per executor node.
max_worker_processesMaximum number of concurrent worker processes.
old_snapshot_thresholdTime before a snapshot is too old to read pages changed after the snapshot was taken.

Resource Usage / Background Writer

bgwriter_delayBackground writer sleep time between rounds.
bgwriter_flush_afterNumber of pages after which previously performed writes are flushed to disk.
bgwriter_lru_maxpagesBackground writer maximum number of LRU pages to flush per round.
bgwriter_lru_multiplierMultiple of the average buffer usage to free per round.

Resource Usage / Cost-Based Vacuum Delay

vacuum_cost_delayVacuum cost delay in milliseconds.
vacuum_cost_limitVacuum cost amount available before napping.
vacuum_cost_page_dirtyVacuum cost for a page dirtied by vacuum.
vacuum_cost_page_hitVacuum cost for a page found in the buffer cache.
vacuum_cost_page_missVacuum cost for a page not found in the buffer cache.

Resource Usage / Disk

temp_file_limitLimits the total size of all temporary files used by each process.

Resource Usage / Kernel Resources

max_files_per_processSets the maximum number of simultaneously open files for each server process.

Resource Usage / Memory

autovacuum_work_memSets the maximum memory to be used by each autovacuum worker process.
dynamic_shared_memory_typeSelects the dynamic shared memory implementation used.
huge_pagesUse of huge pages on Linux.
maintenance_work_memSets the maximum memory to be used for maintenance operations.
max_prepared_transactionsSets the maximum number of simultaneously prepared transactions.
max_stack_depthSets the maximum stack depth, in kilobytes.
replacement_sort_tuplesSets the maximum number of tuples to be sorted using replacement selection.
shared_buffersSets the number of shared memory buffers used by the server.
temp_buffersSets the maximum number of temporary buffers used by each session.
track_activity_query_sizeSets the size reserved for pg_stat_activity.query, in bytes.
work_memSets the maximum memory to be used for query workspaces.

Statistics / Monitoring

Postgresql Commands Cheat Sheet Cheat

log_executor_statsWrites executor performance statistics to the server log.
log_parser_statsWrites parser performance statistics to the server log.
log_planner_statsWrites planner performance statistics to the server log.
log_statement_statsWrites cumulative performance statistics to the server log.

Statistics / Query and Index Statistics Collector

stats_temp_directoryWrites temporary statistics files to the specified directory.
track_activitiesCollects information about executing commands.
track_countsCollects statistics on database activity.
track_functionsCollects function-level statistics on database activity.
track_io_timingCollects timing statistics for database I/O activity.
Postgres shell commands

Version and Platform Compatibility / Other Platforms and Clients

transform_null_equalsTreats “expr=NULL” as “expr IS NULL”.

Version and Platform Compatibility / Previous PostgreSQL Versions

array_nullsEnable input of NULL elements in arrays.
backslash_quoteSets whether “'” is allowed in string literals.
default_with_oidsCreate new tables with OIDs by default.
escape_string_warningWarn about backslash escapes in ordinary string literals.
lo_compat_privilegesEnables backward compatibility mode for privilege checks on large objects.
operator_precedence_warningEmit a warning for constructs that changed meaning since PostgreSQL 9.4.
quote_all_identifiersWhen generating SQL fragments, quote all identifiers.
standard_conforming_stringsCauses ‘…’ strings to treat backslashes literally.
synchronize_seqscansEnable synchronized sequential scans.

Write-Ahead Log / Archiving

archive_commandSets the shell command that will be called to archive a WAL file.
archive_modeAllows archiving of WAL files using archive_command.
archive_timeoutForces a switch to the next WAL file if a new file has not been started within N seconds.

Write-Ahead Log / Checkpoints

checkpoint_completion_targetTime spent flushing dirty buffers during checkpoint, as fraction of checkpoint interval.
checkpoint_flush_afterNumber of pages after which previously performed writes are flushed to disk.
checkpoint_timeoutSets the maximum time between automatic WAL checkpoints.
checkpoint_warningEnables warnings if checkpoint segments are filled more frequently than this.
max_wal_sizeSets the WAL size that triggers a checkpoint.
min_wal_sizeSets the minimum size to shrink the WAL to.

Write-Ahead Log / Settings

commit_delaySets the delay in microseconds between transaction commit and flushing WAL to disk.
commit_siblingsSets the minimum concurrent open transactions before performing commit_delay.
fsyncForces synchronization of updates to disk.
full_page_writesWrites full pages to WAL when first modified after a checkpoint.
synchronous_commitSets the current transaction’s synchronization level.
wal_buffersSets the number of disk-page buffers in shared memory for WAL.
wal_compressionCompresses full-page writes written in WAL file.
wal_levelSet the level of information written to the WAL.
wal_log_hintsWrites full pages to WAL when first modified after a checkpoint, even for a non-critical modifications.
wal_sync_methodSelects the method used for forcing WAL updates to disk.
wal_writer_delayTime between WAL flushes performed in the WAL writer.
wal_writer_flush_afterAmount of WAL written out by WAL writer that triggers a flush.

About pgDash

pgDash is a modern, in-depth monitoring solution designedspecifically for PostgreSQL deployments. pgDash shows you information andmetrics about every aspect of your PostgreSQL database server, collected usingthe open-source tool pgmetrics.

pgDash provides core reporting and visualizationfunctionality, including collecting and displaying PostgreSQL information andproviding time-series graphs, detailed reports, alerting, teams and more.

Starting the server

Windows Users

You must do this every time you restart your machine.

Mac Users

After you have run this command the first time, postgres will start automatically whenever you boot up your computer.

Starting the postgres shell

Open the shell and connect to the city_explorer database:

psql city_explorer

With no arguments, psql will start the shell connected to your user-default database.

Creating a database

This will create a new database called “book_wiki”, which can contain many individual tables:

CREATE DATABASE book_wiki;

Quit the postgres shell

Type the backslash character, immediatly followed by a “q”:

yourname=# q

Basic shell navigation

List all of your databases

yourname=# l

Connect to a database

yourname=# c book_wiki

List all tables (aka: relations) in the database

yourname=# dt

The command dt means “describe table”.

Display the schema for a table

yourname=# d table-name

Troubleshooting Tips

Error - psql not connected to server

psql: could not connect to server: No such file or directory

Postgresql Commands Cheat Sheet Download

Solution - Turn Postgres On

See above notes about starting the server.

Error - schema.sql file not found

When connecting your schema.sql to your database:

schema.sql: No such file or directory

Postgresql Commands Cheat Sheet Free

Solution

You must specify the full path to the .sql file or run the command from the same directory where the .sql file lives.