Server Configuration configuration of the server There are many configuration parameters that affect the behavior of the database system. In the first section of this chapter, we describe how to set configuration parameters. The subsequent sections discuss each parameter in detail. Setting Parameters All parameter names are case-insensitive. Every parameter takes a value of one of five types: Boolean, integer, floating point, string or enum. Boolean values can be written as on, off, true, false, yes, no, 1, 0 (all case-insensitive) or any unambiguous prefix of these. Some settings specify a memory or time value. Each of these has an implicit unit, which is either kilobytes, blocks (typically eight kilobytes), milliseconds, seconds, or minutes. Default units can be found by referencing pg_settings.unit. For convenience, a different unit can also be specified explicitly. Valid memory units are kB (kilobytes), MB (megabytes), and GB (gigabytes); valid time units are ms (milliseconds), s (seconds), min (minutes), h (hours), and d (days). Note that the multiplier for memory units is 1024, not 1000. Parameters of type enum are specified in the same way as string parameters, but are restricted to a limited set of values. The allowed values can be found from pg_settings.enumvals. Enum parameter values are case-insensitive. One way to set these parameters is to edit the file postgresql.confpostgresql.conf, which is normally kept in the data directory. (A default copy is installed there when the database cluster directory is initialized.) An example of what this file might look like is: # This is a comment log_connections = yes log_destination = 'syslog' search_path = '"$user", public' shared_buffers = 128MB One parameter is specified per line. The equal sign between name and value is optional. Whitespace is insignificant and blank lines are ignored. Hash marks (#) designate the rest of the line as a comment. Parameter values that are not simple identifiers or numbers must be single-quoted. To embed a single quote in a parameter value, write either two quotes (preferred) or backslash-quote. include in configuration file In addition to parameter settings, the postgresql.conf file can contain include directives, which specify another file to read and process as if it were inserted into the configuration file at this point. Include directives simply look like: include 'filename' If the file name is not an absolute path, it is taken as relative to the directory containing the referencing configuration file. Inclusions can be nested. SIGHUP The configuration file is reread whenever the main server process receives a SIGHUP signal (which is most easily sent by means of pg_ctl reload). The main server process also propagates this signal to all currently running server processes so that existing sessions also get the new value. Alternatively, you can send the signal to a single server process directly. Some parameters can only be set at server start; any changes to their entries in the configuration file will be ignored until the server is restarted. A second way to set these configuration parameters is to give them as a command-line option to the postgres command, such as: postgres -c log_connections=yes -c log_destination='syslog' Command-line options override any conflicting settings in postgresql.conf. Note that this means you won't be able to change the value on-the-fly by editing postgresql.conf, so while the command-line method might be convenient, it can cost you flexibility later. Occasionally it is useful to give a command line option to one particular session only. The environment variable PGOPTIONS can be used for this purpose on the client side: env PGOPTIONS='-c geqo=off' psql (This works for any libpq-based client application, not just psql.) Note that this won't work for parameters that are fixed when the server is started or that must be specified in postgresql.conf. Furthermore, it is possible to assign a set of parameter settings to a user or a database. Whenever a session is started, the default settings for the user and database involved are loaded. The commands and , respectively, are used to configure these settings. Per-database settings override anything received from the postgres command-line or the configuration file, and in turn are overridden by per-user settings; both are overridden by per-session settings. Some parameters can be changed in individual SQL sessions with the command, for example: SET ENABLE_SEQSCAN TO OFF; If SET is allowed, it overrides all other sources of values for the parameter. Some parameters cannot be changed via SET: for example, if they control behavior that cannot be changed without restarting the entire PostgreSQL server. Also, some SET or ALTER parameter modifications require superuser permission. The command allows inspection of the current values of all parameters. The virtual table pg_settings (described in ) also allows displaying and updating session run-time parameters. It is equivalent to SHOW and SET, but can be more convenient to use because it can be joined with other tables, or selected from using any desired selection condition. It also contains more information about what values are allowed for the parameters. File Locations In addition to the postgresql.conf file already mentioned, PostgreSQL uses two other manually-edited configuration files, which control client authentication (their use is discussed in ). By default, all three configuration files are stored in the database cluster's data directory. The parameters described in this section allow the configuration files to be placed elsewhere. (Doing so can ease administration. In particular it is often easier to ensure that the configuration files are properly backed-up when they are kept separate.) data_directory (string) data_directory configuration parameter Specifies the directory to use for data storage. This parameter can only be set at server start. config_file (string) config_file configuration parameter Specifies the main server configuration file (customarily called postgresql.conf). This parameter can only be set on the postgres command line. hba_file (string) hba_file configuration parameter Specifies the configuration file for host-based authentication (customarily called pg_hba.conf). This parameter can only be set at server start. ident_file (string) ident_file configuration parameter Specifies the configuration file for ident authentication (customarily called pg_ident.conf). This parameter can only be set at server start. external_pid_file (string) external_pid_file configuration parameter Specifies the name of an additional process-id (PID) file that the server should create for use by server administration programs. This parameter can only be set at server start. In a default installation, none of the above parameters are set explicitly. Instead, the data directory is specified by the command-line option or the PGDATA environment variable, and the configuration files are all found within the data directory. If you wish to keep the configuration files elsewhere than the data directory, the postgres command-line option or PGDATA environment variable must point to the directory containing the configuration files, and the data_directory parameter must be set in postgresql.conf (or on the command line) to show where the data directory is actually located. Notice that data_directory overrides and PGDATA for the location of the data directory, but not for the location of the configuration files. If you wish, you can specify the configuration file names and locations individually using the parameters config_file, hba_file and/or ident_file. config_file can only be specified on the postgres command line, but the others can be set within the main configuration file. If all three parameters plus data_directory are explicitly set, then it is not necessary to specify or PGDATA. When setting any of these parameters, a relative path will be interpreted with respect to the directory in which postgres is started. Connections and Authentication Connection Settings listen_addresses (string) listen_addresses configuration parameter Specifies the TCP/IP address(es) on which the server is to listen for connections from client applications. The value takes the form of a comma-separated list of host names and/or numeric IP addresses. The special entry * corresponds to all available IP interfaces. If the list is empty, the server does not listen on any IP interface at all, in which case only Unix-domain sockets can be used to connect to it. The default value is localhost, which allows only local TCP/IP loopback connections to be made. While client authentication () allows fine-grained control over who can access the server, listen_addresses controls which interfaces accept connection attempts, which can help prevent repeated malicious connection requests on insecure network interfaces. This parameter can only be set at server start. port (integer) port configuration parameter The TCP port the server listens on; 5432 by default. Note that the same port number is used for all IP addresses the server listens on. This parameter can only be set at server start. max_connections (integer) max_connections configuration parameter Determines the maximum number of concurrent connections to the database server. The default is typically 100 connections, but might be less if your kernel settings will not support it (as determined during initdb). This parameter can only be set at server start. Increasing this parameter might cause PostgreSQL to request more System V shared memory or semaphores than your operating system's default configuration allows. See for information on how to adjust those parameters, if necessary. When running a standby server, you must set this parameter to the same or higher value than on the master server. Otherwise, queries will not be allowed in the standby server. superuser_reserved_connections (integer) superuser_reserved_connections configuration parameter Determines the number of connection slots that are reserved for connections by PostgreSQL superusers. At most connections can ever be active simultaneously. Whenever the number of active concurrent connections is at least max_connections minus superuser_reserved_connections, new connections will be accepted only for superusers. The default value is three connections. The value must be less than the value of max_connections. This parameter can only be set at server start. unix_socket_directory (string) unix_socket_directory configuration parameter Specifies the directory of the Unix-domain socket on which the server is to listen for connections from client applications. The default is normally /tmp, but can be changed at build time. This parameter can only be set at server start. unix_socket_group (string) unix_socket_group configuration parameter Sets the owning group of the Unix-domain socket. (The owning user of the socket is always the user that starts the server.) In combination with the parameter unix_socket_permissions this can be used as an additional access control mechanism for Unix-domain connections. By default this is the empty string, which uses the default group of the server user. This parameter can only be set at server start. unix_socket_permissions (integer) unix_socket_permissions configuration parameter Sets the access permissions of the Unix-domain socket. Unix-domain sockets use the usual Unix file system permission set. The parameter value is expected to be a numeric mode specified in the format accepted by the chmod and umask system calls. (To use the customary octal format the number must start with a 0 (zero).) The default permissions are 0777, meaning anyone can connect. Reasonable alternatives are 0770 (only user and group, see also unix_socket_group) and 0700 (only user). (Note that for a Unix-domain socket, only write permission matters, so there is no point in setting or revoking read or execute permissions.) This access control mechanism is independent of the one described in . This parameter can only be set at server start. bonjour (boolean) bonjour configuration parameter Enables advertising the server's existence via Bonjour. The default is off. This parameter can only be set at server start. bonjour_name (string) bonjour_name configuration parameter Specifies the Bonjour service name. The computer name is used if this parameter is set to the empty string '' (which is the default). This parameter is ignored if the server was not compiled with Bonjour support. This parameter can only be set at server start. tcp_keepalives_idle (integer) tcp_keepalives_idle configuration parameter On systems that support the TCP_KEEPIDLE socket option, specifies the number of seconds between sending keepalives on an otherwise idle connection. A value of zero uses the system default. If TCP_KEEPIDLE is not supported, this parameter must be zero. This parameter is ignored for connections made via a Unix-domain socket. tcp_keepalives_interval (integer) tcp_keepalives_interval configuration parameter On systems that support the TCP_KEEPINTVL socket option, specifies how long, in seconds, to wait for a response to a keepalive before retransmitting. A value of zero uses the system default. If TCP_KEEPINTVL is not supported, this parameter must be zero. This parameter is ignored for connections made via a Unix-domain socket. tcp_keepalives_count (integer) tcp_keepalives_count configuration parameter On systems that support the TCP_KEEPCNT socket option, specifies how many keepalives can be lost before the connection is considered dead. A value of zero uses the system default. If TCP_KEEPCNT is not supported, this parameter must be zero. This parameter is ignored for connections made via a Unix-domain socket. Security and Authentication authentication_timeout (integer) timeoutclient authentication client authenticationtimeout during authentication_timeout configuration parameter Maximum time to complete client authentication, in seconds. If a would-be client has not completed the authentication protocol in this much time, the server closes the connection. This prevents hung clients from occupying a connection indefinitely. The default is one minute (1m). This parameter can only be set in the postgresql.conf file or on the server command line. ssl (boolean) ssl configuration parameter Enables SSL connections. Please read before using this. The default is off. This parameter can only be set at server start. SSL communication is only possible with TCP/IP connections. ssl_ciphers (string) ssl_ciphers configuration parameter Specifies a list of SSL ciphers that are allowed to be used on secure connections. See the openssl manual page for a list of supported ciphers. password_encryption (boolean) password_encryption configuration parameter When a password is specified in or without writing either ENCRYPTED or UNENCRYPTED, this parameter determines whether the password is to be encrypted. The default is on (encrypt the password). krb_server_keyfile (string) krb_server_keyfile configuration parameter Sets the location of the Kerberos server key file. See or for details. This parameter can only be set in the postgresql.conf file or on the server command line. krb_srvname (string) krb_srvname configuration parameter Sets the Kerberos service name. See for details. This parameter can only be set in the postgresql.conf file or on the server command line. krb_caseins_users (boolean) krb_caseins_users configuration parameter Sets whether Kerberos and GSSAPI user names should be treated case-insensitively. The default is off (case sensitive). This parameter can only be set in the postgresql.conf file or on the server command line. db_user_namespace (boolean) db_user_namespace configuration parameter This parameter enables per-database user names. It is off by default. This parameter can only be set in the postgresql.conf file or on the server command line. If this is on, you should create users as username@dbname. When username is passed by a connecting client, @ and the database name are appended to the user name and that database-specific user name is looked up by the server. Note that when you create users with names containing @ within the SQL environment, you will need to quote the user name. With this parameter enabled, you can still create ordinary global users. Simply append @ when specifying the user name in the client, e.g. joe@. The @ will be stripped off before the user name is looked up by the server. db_user_namespace causes the client's and server's user name representation to differ. Authentication checks are always done with the server's user name so authentication methods must be configured for the server's user name, not the client's. Because md5 uses the user name as salt on both the client and server, md5 cannot be used with db_user_namespace. This feature is intended as a temporary measure until a complete solution is found. At that time, this option will be removed. Resource Consumption Memory shared_buffers (integer) shared_buffers configuration parameter Sets the amount of memory the database server uses for shared memory buffers. The default is typically 32 megabytes (32MB), but might be less if your kernel settings will not support it (as determined during initdb). This setting must be at least 128 kilobytes. (Non-default values of BLCKSZ change the minimum.) However, settings significantly higher than the minimum are usually needed for good performance. Several tens of megabytes are recommended for production installations. This parameter can only be set at server start. Increasing this parameter might cause PostgreSQL to request more System V shared memory than your operating system's default configuration allows. See for information on how to adjust those parameters, if necessary. temp_buffers (integer) temp_buffers configuration parameter Sets the maximum number of temporary buffers used by each database session. These are session-local buffers used only for access to temporary tables. The default is eight megabytes (8MB). The setting can be changed within individual sessions, but only before the first use of temporary tables within the session; subsequent attempts to change the value will have no effect on that session. A session will allocate temporary buffers as needed up to the limit given by temp_buffers. The cost of setting a large value in sessions that do not actually need many temporary buffers is only a buffer descriptor, or about 64 bytes, per increment in temp_buffers. However if a buffer is actually used an additional 8192 bytes will be consumed for it (or in general, BLCKSZ bytes). max_prepared_transactions (integer) max_prepared_transactions configuration parameter Sets the maximum number of transactions that can be in the prepared state simultaneously (see ). Setting this parameter to zero (which is the default) disables the prepared-transaction feature. This parameter can only be set at server start. If you are not planning to use prepared transactions, this parameter should be set to zero to prevent accidental creation of prepared transactions. If you are using prepared transactions, you will probably want max_prepared_transactions to be at least as large as , so that every session can have a prepared transaction pending. Increasing this parameter might cause PostgreSQL to request more System V shared memory than your operating system's default configuration allows. See for information on how to adjust those parameters, if necessary. When running a standby server, you must set this parameter to the same or higher value than on the master server. Otherwise, queries will not be allowed in the standby server. work_mem (integer) work_mem configuration parameter Specifies the amount of memory to be used by internal sort operations and hash tables before writing to temporary disk files. The value defaults to one megabyte (1MB). Note that for a complex query, several sort or hash operations might be running in parallel; each operation will be allowed to use as much memory as this value specifies before it starts to write data into temporary files. Also, several running sessions could be doing such operations concurrently. Therefore, the total memory used could be many times the value of work_mem; it is necessary to keep this fact in mind when choosing the value. Sort operations are used for ORDER BY, DISTINCT, and merge joins. Hash tables are used in hash joins, hash-based aggregation, and hash-based processing of IN subqueries. maintenance_work_mem (integer) maintenance_work_mem configuration parameter Specifies the maximum amount of memory to be used by maintenance operations, such as VACUUM, CREATE INDEX, and ALTER TABLE ADD FOREIGN KEY. It defaults to 16 megabytes (16MB). Since only one of these operations can be executed at a time by a database session, and an installation normally doesn't have many of them running concurrently, it's safe to set this value significantly larger than work_mem. Larger settings might improve performance for vacuuming and for restoring database dumps. Note that when autovacuum runs, up to times this memory may be allocated, so be careful not to set the default value too high. max_stack_depth (integer) max_stack_depth configuration parameter Specifies the maximum safe depth of the server's execution stack. The ideal setting for this parameter is the actual stack size limit enforced by the kernel (as set by ulimit -s or local equivalent), less a safety margin of a megabyte or so. The safety margin is needed because the stack depth is not checked in every routine in the server, but only in key potentially-recursive routines such as expression evaluation. The default setting is two megabytes (2MB), which is conservatively small and unlikely to risk crashes. However, it might be too small to allow execution of complex functions. Only superusers can change this setting. Setting max_stack_depth higher than the actual kernel limit will mean that a runaway recursive function can crash an individual backend process. On platforms where PostgreSQL can determine the kernel limit, the server will not allow this variable to be set to an unsafe value. However, not all platforms provide the information, so caution is recommended in selecting a value. Kernel Resource Usage max_files_per_process (integer) max_files_per_process configuration parameter Sets the maximum number of simultaneously open files allowed to each server subprocess. The default is one thousand files. If the kernel is enforcing a safe per-process limit, you don't need to worry about this setting. But on some platforms (notably, most BSD systems), the kernel will allow individual processes to open many more files than the system can actually support if many processes all try to open that many files. If you find yourself seeing Too many open files failures, try reducing this setting. This parameter can only be set at server start. shared_preload_libraries (string) shared_preload_libraries configuration parameter This variable specifies one or more shared libraries to be preloaded at server start. For example, '$libdir/mylib' would cause mylib.so (or on some platforms, mylib.sl) to be preloaded from the installation's standard library directory. If more than one library is to be loaded, separate their names with commas. This parameter can only be set at server start. PostgreSQL procedural language libraries can be preloaded in this way, typically by using the syntax '$libdir/plXXX' where XXX is pgsql, perl, tcl, or python. By preloading a shared library, the library startup time is avoided when the library is first used. However, the time to start each new server process might increase slightly, even if that process never uses the library. So this parameter is recommended only for libraries that will be used in most sessions. On Windows hosts, preloading a library at server start will not reduce the time required to start each new server process; each server process will re-load all preload libraries. However, shared_preload_libraries is still useful on Windows hosts because some shared libraries may need to perform certain operations that only take place at postmaster start (for example, a shared library may need to reserve lightweight locks or shared memory and you can't do that after the postmaster has started). If a specified library is not found, the server will fail to start. Every PostgreSQL-supported library has a magic block that is checked to guarantee compatibility. For this reason, non-PostgreSQL libraries cannot be loaded in this way. Cost-Based Vacuum Delay During the execution of and commands, the system maintains an internal counter that keeps track of the estimated cost of the various I/O operations that are performed. When the accumulated cost reaches a limit (specified by vacuum_cost_limit), the process performing the operation will sleep for a short period of time, as specified by vacuum_cost_delay. Then it will reset the counter and continue execution. The intent of this feature is to allow administrators to reduce the I/O impact of these commands on concurrent database activity. There are many situations where it is not important that maintenance commands like VACUUM and ANALYZE finish quickly; however, it is usually very important that these commands do not significantly interfere with the ability of the system to perform other database operations. Cost-based vacuum delay provides a way for administrators to achieve this. This feature is disabled by default for manually issued VACUUM commands. To enable it, set the vacuum_cost_delay variable to a nonzero value. vacuum_cost_delay (integer) vacuum_cost_delay configuration parameter The length of time, in milliseconds, that the process will sleep when the cost limit has been exceeded. The default value is zero, which disables the cost-based vacuum delay feature. Positive values enable cost-based vacuuming. Note that on many systems, the effective resolution of sleep delays is 10 milliseconds; setting vacuum_cost_delay to a value that is not a multiple of 10 might have the same results as setting it to the next higher multiple of 10. When using cost-based vacuuming, appropriate values for vacuum_cost_delay are usually quite small, perhaps 10 or 20 milliseconds. Adjusting vacuum's resource consumption is best done by changing the other vacuum cost parameters. vacuum_cost_page_hit (integer) vacuum_cost_page_hit configuration parameter The estimated cost for vacuuming a buffer found in the shared buffer cache. It represents the cost to lock the buffer pool, lookup the shared hash table and scan the content of the page. The default value is one. vacuum_cost_page_miss (integer) vacuum_cost_page_miss configuration parameter The estimated cost for vacuuming a buffer that has to be read from disk. This represents the effort to lock the buffer pool, lookup the shared hash table, read the desired block in from the disk and scan its content. The default value is 10. vacuum_cost_page_dirty (integer) vacuum_cost_page_dirty configuration parameter The estimated cost charged when vacuum modifies a block that was previously clean. It represents the extra I/O required to flush the dirty block out to disk again. The default value is 20. vacuum_cost_limit (integer) vacuum_cost_limit configuration parameter The accumulated cost that will cause the vacuuming process to sleep. The default value is 200. There are certain operations that hold critical locks and should therefore complete as quickly as possible. Cost-based vacuum delays do not occur during such operations. Therefore it is possible that the cost accumulates far higher than the specified limit. To avoid uselessly long delays in such cases, the actual delay is calculated as vacuum_cost_delay * accumulated_balance / vacuum_cost_limit with a maximum of vacuum_cost_delay * 4. Background Writer There is a separate server process called the background writer, whose function is to issue writes of dirty (new or modified) shared buffers. It writes shared buffers so server processes handling user queries seldom or never need to wait for a write to occur. However, the background writer does cause a net overall increase in I/O load, because while a repeatedly-dirtied page might otherwise be written only once per checkpoint interval, the background writer might write it several times as it is dirtied in the same interval. The parameters discussed in this subsection can be used to tune the behavior for local needs. bgwriter_delay (integer) bgwriter_delay configuration parameter Specifies the delay between activity rounds for the background writer. In each round the writer issues writes for some number of dirty buffers (controllable by the following parameters). It then sleeps for bgwriter_delay milliseconds, and repeats. The default value is 200 milliseconds (200ms). Note that on many systems, the effective resolution of sleep delays is 10 milliseconds; setting bgwriter_delay to a value that is not a multiple of 10 might have the same results as setting it to the next higher multiple of 10. This parameter can only be set in the postgresql.conf file or on the server command line. bgwriter_lru_maxpages (integer) bgwriter_lru_maxpages configuration parameter In each round, no more than this many buffers will be written by the background writer. Setting this to zero disables background writing (except for checkpoint activity). The default value is 100 buffers. This parameter can only be set in the postgresql.conf file or on the server command line. bgwriter_lru_multiplier (floating point) bgwriter_lru_multiplier configuration parameter The number of dirty buffers written in each round is based on the number of new buffers that have been needed by server processes during recent rounds. The average recent need is multiplied by bgwriter_lru_multiplier to arrive at an estimate of the number of buffers that will be needed during the next round. Dirty buffers are written until there are that many clean, reusable buffers available. (However, no more than bgwriter_lru_maxpages buffers will be written per round.) Thus, a setting of 1.0 represents a just in time policy of writing exactly the number of buffers predicted to be needed. Larger values provide some cushion against spikes in demand, while smaller values intentionally leave writes to be done by server processes. The default is 2.0. This parameter can only be set in the postgresql.conf file or on the server command line. Smaller values of bgwriter_lru_maxpages and bgwriter_lru_multiplier reduce the extra I/O load caused by the background writer, but make it more likely that server processes will have to issue writes for themselves, delaying interactive queries. Asynchronous Behavior effective_io_concurrency (integer) effective_io_concurrency configuration parameter Sets the number of concurrent disk I/O operations that PostgreSQL expects can be executed simultaneously. Raising this value will increase the number of I/O operations that any individual PostgreSQL session attempts to initiate in parallel. The allowed range is 1 to 1000, or zero to disable issuance of asynchronous I/O requests. A good starting point for this setting is the number of separate drives comprising a RAID 0 stripe or RAID 1 mirror being used for the database. (For RAID 5 the parity drive should not be counted.) However, if the database is often busy with multiple queries issued in concurrent sessions, lower values may be sufficient to keep the disk array busy. A value higher than needed to keep the disks busy will only result in extra CPU overhead. For more exotic systems, such as memory-based storage or a RAID array that is limited by bus bandwidth, the correct value might be the number of I/O paths available. Some experimentation may be needed to find the best value. Asynchronous I/O depends on an effective posix_fadvise function, which some operating systems lack. If the function is not present then setting this parameter to anything but zero will result in an error. On some operating systems (e.g., Solaris), the function is present but does not actually do anything. Write Ahead Log See also for details on WAL and checkpoint tuning. Settings fsync configuration parameter fsync (boolean) If this parameter is on, the PostgreSQL server will try to make sure that updates are physically written to disk, by issuing fsync() system calls or various equivalent methods (see ). This ensures that the database cluster can recover to a consistent state after an operating system or hardware crash. However, using fsync results in a performance penalty: when a transaction is committed, PostgreSQL must wait for the operating system to flush the write-ahead log to disk. When fsync is disabled, the operating system is allowed to do its best in buffering, ordering, and delaying writes. This can result in significantly improved performance. However, if the system crashes, the results of the last few committed transactions might be completely lost, or worse, might appear partially committed, leaving the database in an inconsistent state. In the worst case, unrecoverable data corruption might occur. (Crashes of the database software itself are not a risk factor here. Only an operating-system-level crash creates a risk of corruption.) Due to the risks involved, there is no universally correct setting for fsync. Some administrators always disable fsync, while others only turn it off during initial bulk data loads, where there is a clear restart point if something goes wrong. Others always leave fsync enabled. The default is to enable fsync, for maximum reliability. If you trust your operating system, your hardware, and your utility company (or your battery backup), you can consider disabling fsync. In many situations, turning off for noncritical transactions can provide much of the potential performance benefit of turning off fsync, without the attendant risks of data corruption. fsync can only be set in the postgresql.conf file or on the server command line. If you turn this parameter off, also consider turning off . synchronous_commit (boolean) synchronous_commit configuration parameter Specifies whether transaction commit will wait for WAL records to be written to disk before the command returns a success indication to the client. The default, and safe, setting is on. When off, there can be a delay between when success is reported to the client and when the transaction is really guaranteed to be safe against a server crash. (The maximum delay is three times .) Unlike , setting this parameter to off does not create any risk of database inconsistency: a crash might result in some recent allegedly-committed transactions being lost, but the database state will be just the same as if those transactions had been aborted cleanly. So, turning synchronous_commit off can be a useful alternative when performance is more important than exact certainty about the durability of a transaction. For more discussion see . This parameter can be changed at any time; the behavior for any one transaction is determined by the setting in effect when it commits. It is therefore possible, and useful, to have some transactions commit synchronously and others asynchronously. For example, to make a single multi-statement transaction commit asynchronously when the default is the opposite, issue SET LOCAL synchronous_commit TO OFF within the transaction. wal_sync_method (enum) wal_sync_method configuration parameter Method used for forcing WAL updates out to disk. If fsync is off then this setting is irrelevant, since WAL file updates will not be forced out at all. Possible values are: open_datasync (write WAL files with open() option O_DSYNC) fdatasync (call fdatasync() at each commit) fsync_writethrough (call fsync() at each commit, forcing write-through of any disk write cache) fsync (call fsync() at each commit) open_sync (write WAL files with open() option O_SYNC) Not all of these choices are available on all platforms. The default is the first method in the above list that is supported by the platform. The open_* options also use O_DIRECT if available. The utility src/tools/fsync in the PostgreSQL source tree can do performance testing of various fsync methods. This parameter can only be set in the postgresql.conf file or on the server command line. full_page_writes configuration parameter full_page_writes (boolean) When this parameter is on, the PostgreSQL server writes the entire content of each disk page to WAL during the first modification of that page after a checkpoint. This is needed because a page write that is in process during an operating system crash might be only partially completed, leading to an on-disk page that contains a mix of old and new data. The row-level change data normally stored in WAL will not be enough to completely restore such a page during post-crash recovery. Storing the full page image guarantees that the page can be correctly restored, but at the price of increasing the amount of data that must be written to WAL. (Because WAL replay always starts from a checkpoint, it is sufficient to do this during the first change of each page after a checkpoint. Therefore, one way to reduce the cost of full-page writes is to increase the checkpoint interval parameters.) Turning this parameter off speeds normal operation, but might lead to a corrupt database after an operating system crash or power failure. The risks are similar to turning off fsync, though smaller. It might be safe to turn off this parameter if you have hardware (such as a battery-backed disk controller) or file-system software that reduces the risk of partial page writes to an acceptably low level (e.g., ZFS). Turning off this parameter does not affect use of WAL archiving for point-in-time recovery (PITR) (see ). This parameter can only be set in the postgresql.conf file or on the server command line. The default is on. wal_buffers (integer) wal_buffers configuration parameter The amount of memory used in shared memory for WAL data. The default is 64 kilobytes (64kB). The setting need only be large enough to hold the amount of WAL data generated by one typical transaction, since the data is written out to disk at every transaction commit. This parameter can only be set at server start. Increasing this parameter might cause PostgreSQL to request more System V shared memory than your operating system's default configuration allows. See for information on how to adjust those parameters, if necessary. wal_writer_delay (integer) wal_writer_delay configuration parameter Specifies the delay between activity rounds for the WAL writer. In each round the writer will flush WAL to disk. It then sleeps for wal_writer_delay milliseconds, and repeats. The default value is 200 milliseconds (200ms). Note that on many systems, the effective resolution of sleep delays is 10 milliseconds; setting wal_writer_delay to a value that is not a multiple of 10 might have the same results as setting it to the next higher multiple of 10. This parameter can only be set in the postgresql.conf file or on the server command line. commit_delay (integer) commit_delay configuration parameter Time delay between writing a commit record to the WAL buffer and flushing the buffer out to disk, in microseconds. A nonzero delay can allow multiple transactions to be committed with only one fsync() system call, if system load is high enough that additional transactions become ready to commit within the given interval. But the delay is just wasted if no other transactions become ready to commit. Therefore, the delay is only performed if at least commit_siblings other transactions are active at the instant that a server process has written its commit record. The default is zero (no delay). commit_siblings (integer) commit_siblings configuration parameter Minimum number of concurrent open transactions to require before performing the commit_delay delay. A larger value makes it more probable that at least one other transaction will become ready to commit during the delay interval. The default is five transactions. Checkpoints checkpoint_segments (integer) checkpoint_segments configuration parameter Maximum number of log file segments between automatic WAL checkpoints (each segment is normally 16 megabytes). The default is three segments. Increasing this parameter can increase the amount of time needed for crash recovery. This parameter can only be set in the postgresql.conf file or on the server command line. checkpoint_timeout (integer) checkpoint_timeout configuration parameter Maximum time between automatic WAL checkpoints, in seconds. The default is five minutes (5min). Increasing this parameter can increase the amount of time needed for crash recovery. This parameter can only be set in the postgresql.conf file or on the server command line. checkpoint_completion_target (floating point) checkpoint_completion_target configuration parameter Specifies the target of checkpoint completion, as a fraction of total time between checkpoints. The default is 0.5. This parameter can only be set in the postgresql.conf file or on the server command line. checkpoint_warning (integer) checkpoint_warning configuration parameter Write a message to the server log if checkpoints caused by the filling of checkpoint segment files happen closer together than this many seconds (which suggests that checkpoint_segments ought to be raised). The default is 30 seconds (30s). Zero disables the warning. This parameter can only be set in the postgresql.conf file or on the server command line. Archiving archive_mode (boolean) archive_mode configuration parameter When archive_mode is enabled, completed WAL segments are sent to archive storage by setting . archive_mode and archive_command are separate variables so that archive_command can be changed without leaving archiving mode. This parameter can only be set at server start. archive_command (string) archive_command configuration parameter The shell command to execute to archive a completed WAL file segment. Any %p in the string is replaced by the path name of the file to archive, and any %f is replaced by only the file name. (The path name is relative to the working directory of the server, i.e., the cluster's data directory.) Use %% to embed an actual % character in the command. For more information see . This parameter can only be set in the postgresql.conf file or on the server command line. It is ignored unless archive_mode was enabled at server start. If archive_command is an empty string (the default) while archive_mode is enabled, WAL archiving is temporarily disabled, but the server continues to accumulate WAL segment files in the expectation that a command will soon be provided. Setting archive_mode to a command that does nothing but return true, e.g. /bin/true, effectively disables archiving, but also breaks the chain of WAL files needed for archive recovery, so it should only be used in unusual circumstances. It is important for the command to return a zero exit status if and only if it succeeds. Examples: archive_command = 'cp "%p" /mnt/server/archivedir/"%f"' archive_command = 'copy "%p" "C:\\server\\archivedir\\%f"' # Windows archive_timeout (integer) archive_timeout configuration parameter The is only invoked for completed WAL segments. Hence, if your server generates little WAL traffic (or has slack periods where it does so), there could be a long delay between the completion of a transaction and its safe recording in archive storage. To limit how old unarchived data can be, you can set archive_timeout to force the server to switch to a new WAL segment file periodically. When this parameter is greater than zero, the server will switch to a new segment file whenever this many seconds have elapsed since the last segment file switch, and there has been any database activity, including a single checkpoint. (Increasing checkpoint_timeout will reduce unnecessary checkpoints on an idle system.) Note that archived files that are closed early due to a forced switch are still the same length as completely full files. Therefore, it is unwise to use a very short archive_timeout — it will bloat your archive storage. archive_timeout settings of a minute or so are usually reasonable. This parameter can only be set in the postgresql.conf file or on the server command line. Streaming Replication These settings control the behavior of the built-in streaming replication feature. max_wal_senders (integer) max_wal_senders configuration parameter Specifies the maximum number of concurrent connections from standby servers (i.e., the maximum number of simultaneously running WAL sender processes). The default is zero. This parameter can only be set at server start. wal_sender_delay (integer) wal_sender_delay configuration parameter Specifies the delay between activity rounds for the WAL sender. In each round the WAL sender sends any WAL accumulated since last round to the standby server. It then sleeps for wal_sender_delay milliseconds, and repeats. The default value is 200 milliseconds (200ms). Note that on many systems, the effective resolution of sleep delays is 10 milliseconds; setting wal_sender_delay to a value that is not a multiple of 10 might have the same results as setting it to the next higher multiple of 10. This parameter can only be set in the postgresql.conf file or on the server command line. Standby Servers recovery_connections (boolean) recovery_connections configuration parameter Parameter has two roles. During recovery, specifies whether or not you can connect and run queries to enable . During normal running, specifies whether additional information is written to WAL to allow recovery connections on a standby server that reads WAL data generated by this server. The default value is on. It is thought that there is little measurable difference in performance from using this feature, so feedback is welcome if any production impacts are noticeable. It is likely that this parameter will be removed in later releases. This parameter can only be set at server start. max_standby_delay (string) max_standby_delay configuration parameter When server acts as a standby, this parameter specifies a wait policy for queries that conflict with data changes being replayed by recovery. If a conflict should occur the server will delay up to this number of seconds before it begins trying to resolve things less amicably, as described in . Typically, this parameter makes sense only during replication, so when performing an archive recovery to recover from data loss a very high parameter setting is recommended. The default is 30 seconds. There is no wait-forever setting because of the potential for deadlock which that setting would introduce. This parameter can only be set in the postgresql.conf file or on the server command line. Query Planning Planner Method Configuration These configuration parameters provide a crude method of influencing the query plans chosen by the query optimizer. If the default plan chosen by the optimizer for a particular query is not optimal, a temporary solution is to use one of these configuration parameters to force the optimizer to choose a different plan. Better ways to improve the quality of the plans chosen by the optimizer include adjusting the , running manually, increasing the value of the configuration parameter, and increasing the amount of statistics collected for specific columns using ALTER TABLE SET STATISTICS. enable_bitmapscan (boolean) bitmap scan enable_bitmapscan configuration parameter Enables or disables the query planner's use of bitmap-scan plan types. The default is on. enable_hashagg (boolean) enable_hashagg configuration parameter Enables or disables the query planner's use of hashed aggregation plan types. The default is on. enable_hashjoin (boolean) enable_hashjoin configuration parameter Enables or disables the query planner's use of hash-join plan types. The default is on. enable_indexscan (boolean) index scan enable_indexscan configuration parameter Enables or disables the query planner's use of index-scan plan types. The default is on. enable_mergejoin (boolean) enable_mergejoin configuration parameter Enables or disables the query planner's use of merge-join plan types. The default is on. enable_nestloop (boolean) enable_nestloop configuration parameter Enables or disables the query planner's use of nested-loop join plans. It is impossible to suppress nested-loop joins entirely, but turning this variable off discourages the planner from using one if there are other methods available. The default is on. enable_seqscan (boolean) sequential scan enable_seqscan configuration parameter Enables or disables the query planner's use of sequential scan plan types. It is impossible to suppress sequential scans entirely, but turning this variable off discourages the planner from using one if there are other methods available. The default is on. enable_sort (boolean) enable_sort configuration parameter Enables or disables the query planner's use of explicit sort steps. It is impossible to suppress explicit sorts entirely, but turning this variable off discourages the planner from using one if there are other methods available. The default is on. enable_tidscan (boolean) enable_tidscan configuration parameter Enables or disables the query planner's use of TID scan plan types. The default is on. Planner Cost Constants The cost variables described in this section are measured on an arbitrary scale. Only their relative values matter, hence scaling them all up or down by the same factor will result in no change in the planner's choices. By default, these cost variables are based on the cost of sequential page fetches; that is, seq_page_cost is conventionally set to 1.0 and the other cost variables are set with reference to that. But you can use a different scale if you prefer, such as actual execution times in milliseconds on a particular machine. Unfortunately, there is no well-defined method for determining ideal values for the cost variables. They are best treated as averages over the entire mix of queries that a particular installation will receive. This means that changing them on the basis of just a few experiments is very risky. seq_page_cost (floating point) seq_page_cost configuration parameter Sets the planner's estimate of the cost of a disk page fetch that is part of a series of sequential fetches. The default is 1.0. This value can be overriden for a particular tablespace by setting the tablespace parameter of the same name (see ). random_page_cost (floating point) random_page_cost configuration parameter Sets the planner's estimate of the cost of a non-sequentially-fetched disk page. The default is 4.0. This value can be overriden for a particular tablespace by setting the tablespace parameter of the same name (see ). Reducing this value relative to seq_page_cost will cause the system to prefer index scans; raising it will make index scans look relatively more expensive. You can raise or lower both values together to change the importance of disk I/O costs relative to CPU costs, which are described by the following parameters. Although the system will let you set random_page_cost to less than seq_page_cost, it is not physically sensible to do so. However, setting them equal makes sense if the database is entirely cached in RAM, since in that case there is no penalty for touching pages out of sequence. Also, in a heavily-cached database you should lower both values relative to the CPU parameters, since the cost of fetching a page already in RAM is much smaller than it would normally be. cpu_tuple_cost (floating point) cpu_tuple_cost configuration parameter Sets the planner's estimate of the cost of processing each row during a query. The default is 0.01. cpu_index_tuple_cost (floating point) cpu_index_tuple_cost configuration parameter Sets the planner's estimate of the cost of processing each index entry during an index scan. The default is 0.005. cpu_operator_cost (floating point) cpu_operator_cost configuration parameter Sets the planner's estimate of the cost of processing each operator or function executed during a query. The default is 0.0025. effective_cache_size (integer) effective_cache_size configuration parameter Sets the planner's assumption about the effective size of the disk cache that is available to a single query. This is factored into estimates of the cost of using an index; a higher value makes it more likely index scans will be used, a lower value makes it more likely sequential scans will be used. When setting this parameter you should consider both PostgreSQL's shared buffers and the portion of the kernel's disk cache that will be used for PostgreSQL data files. Also, take into account the expected number of concurrent queries on different tables, since they will have to share the available space. This parameter has no effect on the size of shared memory allocated by PostgreSQL, nor does it reserve kernel disk cache; it is used only for estimation purposes. The default is 128 megabytes (128MB). Genetic Query Optimizer The genetic query optimizer (GEQO) is an algorithm that does query planning using heuristic searching. This reduces planning time for complex queries (those joining many relations), at the cost of producing plans that are sometimes inferior to those found by the normal exhaustive-search algorithm. Also, GEQO's searching is randomized and therefore its plans may vary nondeterministically. For more information see . genetic query optimization GEQO genetic query optimization geqo configuration parameter geqo (boolean) Enables or disables genetic query optimization. This is on by default. It is usually best not to turn it off in production; the geqo_threshold variable provides more granular control of GEQO. geqo_threshold (integer) geqo_threshold configuration parameter Use genetic query optimization to plan queries with at least this many FROM items involved. (Note that a FULL OUTER JOIN construct counts as only one FROM item.) The default is 12. For simpler queries it is usually best to use the deterministic, exhaustive planner, but for queries with many tables the deterministic planner takes too long, often longer than the penalty of executing a suboptimal plan. geqo_effort (integer) geqo_effort configuration parameter Controls the trade-off between planning time and query plan quality in GEQO. This variable must be an integer in the range from 1 to 10. The default value is five. Larger values increase the time spent doing query planning, but also increase the likelihood that an efficient query plan will be chosen. geqo_effort doesn't actually do anything directly; it is only used to compute the default values for the other variables that influence GEQO behavior (described below). If you prefer, you can set the other parameters by hand instead. geqo_pool_size (integer) geqo_pool_size configuration parameter Controls the pool size used by GEQO, that is the number of individuals in the genetic population. It must be at least two, and useful values are typically 100 to 1000. If it is set to zero (the default setting) then a suitable value is chosen based on geqo_effort and the number of tables in the query. geqo_generations (integer) geqo_generations configuration parameter Controls the number of generations used by GEQO, that is the number of iterations of the algorithm. It must be at least one, and useful values are in the same range as the pool size. If it is set to zero (the default setting) then a suitable value is chosen based on geqo_pool_size. geqo_selection_bias (floating point) geqo_selection_bias configuration parameter Controls the selection bias used by GEQO. The selection bias is the selective pressure within the population. Values can be from 1.50 to 2.00; the latter is the default. geqo_seed (floating point) geqo_seed configuration parameter Controls the initial value of the random number generator used by GEQO to select random paths through the join order search space. The value can range from zero (the default) to one. Varying the value changes the set of join paths explored, and may result in a better or worse best path being found. Other Planner Options default_statistics_target (integer) default_statistics_target configuration parameter Sets the default statistics target for table columns without a column-specific target set via ALTER TABLE SET STATISTICS. Larger values increase the time needed to do ANALYZE, but might improve the quality of the planner's estimates. The default is 100. For more information on the use of statistics by the PostgreSQL query planner, refer to . constraint_exclusion (enum) constraint exclusion constraint_exclusion configuration parameter Controls the query planner's use of table constraints to optimize queries. The allowed values of constraint_exclusion are on (examine constraints for all tables), off (never examine constraints), and partition (examine constraints only for inheritance child tables and UNION ALL subqueries). partition is the default setting. It is often used with inheritance and partitioned tables to improve performance. When this parameter allows it for a particular table, the planner compares query conditions with the table's CHECK constraints, and omits scanning tables for which the conditions contradict the constraints. For example: CREATE TABLE parent(key integer, ...); CREATE TABLE child1000(check (key between 1000 and 1999)) INHERITS(parent); CREATE TABLE child2000(check (key between 2000 and 2999)) INHERITS(parent); ... SELECT * FROM parent WHERE key = 2400; With constraint exclusion enabled, this SELECT will not scan child1000 at all, improving performance. Currently, constraint exclusion is enabled by default only for cases that are often used to implement table partitioning. Turning it on for all tables imposes extra planning overhead that is quite noticeable on simple queries, and most often will yield no benefit for simple queries. If you have no partitioned tables you might prefer to turn it off entirely. Refer to for more information on using constraint exclusion and partitioning. cursor_tuple_fraction (floating point) cursor_tuple_fraction configuration parameter Sets the planner's estimate of the fraction of a cursor's rows that will be retrieved. The default is 0.1. Smaller values of this setting bias the planner towards using fast start plans for cursors, which will retrieve the first few rows quickly while perhaps taking a long time to fetch all rows. Larger values put more emphasis on the total estimated time. At the maximum setting of 1.0, cursors are planned exactly like regular queries, considering only the total estimated time and not how soon the first rows might be delivered. from_collapse_limit (integer) from_collapse_limit configuration parameter The planner will merge sub-queries into upper queries if the resulting FROM list would have no more than this many items. Smaller values reduce planning time but might yield inferior query plans. The default is eight. For more information see . Setting this value to or more may trigger use of the GEQO planner, resulting in nondeterministic plans. See . join_collapse_limit (integer) join_collapse_limit configuration parameter The planner will rewrite explicit JOIN constructs (except FULL JOINs) into lists of FROM items whenever a list of no more than this many items would result. Smaller values reduce planning time but might yield inferior query plans. By default, this variable is set the same as from_collapse_limit, which is appropriate for most uses. Setting it to 1 prevents any reordering of explicit JOINs. Thus, the explicit join order specified in the query will be the actual order in which the relations are joined. Because the query planner does not always choose the optimal join order, advanced users can elect to temporarily set this variable to 1, and then specify the join order they desire explicitly. For more information see . Setting this value to or more may trigger use of the GEQO planner, resulting in nondeterministic plans. See . Error Reporting and Logging server log Where To Log where to log log_destination (string) log_destination configuration parameter PostgreSQL supports several methods for logging server messages, including stderr, csvlog and syslog. On Windows, eventlog is also supported. Set this parameter to a list of desired log destinations separated by commas. The default is to log to stderr only. This parameter can only be set in the postgresql.conf file or on the server command line. If csvlog is included in log_destination, log entries are output in comma separated value (CSV) format, which is convenient for loading logs into programs. See for details. logging_collector must be enabled to generate CSV-format log output. On most Unix systems, you will need to alter the configuration of your system's syslog daemon in order to make use of the syslog option for log_destination. PostgreSQL can log to syslog facilities LOCAL0 through LOCAL7 (see ), but the default syslog configuration on most platforms will discard all such messages. You will need to add something like: local0.* /var/log/postgresql to the syslog daemon's configuration file to make it work. logging_collector (boolean) logging_collector configuration parameter This parameter captures plain and CSV-format log messages sent to stderr and redirects them into log files. This approach is often more useful than logging to syslog, since some types of messages might not appear in syslog output (a common example is dynamic-linker failure messages). This parameter can only be set at server start. The logging collector is designed to never lose messages. This means that in case of extremely high load, server processes could be blocked due to trying to send additional log messages when the collector has fallen behind. In contrast, syslog prefers to drop messages if it cannot write them, which means it's less reliable in those cases but it will not block the rest of the system. log_directory (string) log_directory configuration parameter When logging_collector is enabled, this parameter determines the directory in which log files will be created. It can be specified as an absolute path, or relative to the cluster data directory. This parameter can only be set in the postgresql.conf file or on the server command line. log_filename (string) log_filename configuration parameter When logging_collector is enabled, this parameter sets the file names of the created log files. The value is treated as a strftime pattern, so %-escapes can be used to specify time-varying file names. (Note that if there are any time-zone-dependent %-escapes, the computation is done in the zone specified by .) Note that the system's strftime is not used directly, so platform-specific (nonstandard) extensions do not work. If you specify a file name without escapes, you should plan to use a log rotation utility to avoid eventually filling the entire disk. In releases prior to 8.4, if no % escapes were present, PostgreSQL would append the epoch of the new log file's creation time, but this is no longer the case. If CSV-format output is enabled in log_destination, .csv will be appended to the timestamped log file name to create the file name for CSV-format output. (If log_filename ends in .log, the suffix is replaced instead.) In the case of the example above, the CSV file name will be server_log.1093827753.csv. This parameter can only be set in the postgresql.conf file or on the server command line. log_rotation_age (integer) log_rotation_age configuration parameter When logging_collector is enabled, this parameter determines the maximum lifetime of an individual log file. After this many minutes have elapsed, a new log file will be created. Set to zero to disable time-based creation of new log files. This parameter can only be set in the postgresql.conf file or on the server command line. log_rotation_size (integer) log_rotation_size configuration parameter When logging_collector is enabled, this parameter determines the maximum size of an individual log file. After this many kilobytes have been emitted into a log file, a new log file will be created. Set to zero to disable size-based creation of new log files. This parameter can only be set in the postgresql.conf file or on the server command line. log_truncate_on_rotation (boolean) log_truncate_on_rotation configuration parameter When logging_collector is enabled, this parameter will cause PostgreSQL to truncate (overwrite), rather than append to, any existing log file of the same name. However, truncation will occur only when a new file is being opened due to time-based rotation, not during server startup or size-based rotation. When off, pre-existing files will be appended to in all cases. For example, using this setting in combination with a log_filename like postgresql-%H.log would result in generating twenty-four hourly log files and then cyclically overwriting them. This parameter can only be set in the postgresql.conf file or on the server command line. Example: To keep 7 days of logs, one log file per day named server_log.Mon, server_log.Tue, etc, and automatically overwrite last week's log with this week's log, set log_filename to server_log.%a, log_truncate_on_rotation to on, and log_rotation_age to 1440. Example: To keep 24 hours of logs, one log file per hour, but also rotate sooner if the log file size exceeds 1GB, set log_filename to server_log.%H%M, log_truncate_on_rotation to on, log_rotation_age to 60, and log_rotation_size to 1000000. Including %M in log_filename allows any size-driven rotations that might occur to select a file name different from the hour's initial file name. syslog_facility (enum) syslog_facility configuration parameter When logging to syslog is enabled, this parameter determines the syslog facility to be used. You can choose from LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7; the default is LOCAL0. See also the documentation of your system's syslog daemon. This parameter can only be set in the postgresql.conf file or on the server command line. syslog_ident (string) syslog_identity configuration parameter When logging to syslog is enabled, this parameter determines the program name used to identify PostgreSQL messages in syslog logs. The default is postgres. This parameter can only be set in the postgresql.conf file or on the server command line. silent_mode (boolean) silent_mode configuration parameter Runs the server silently. If this parameter is set, the server will automatically run in background and disassociate from the controlling terminal. This parameter can only be set at server start. When this parameter is set, the server's standard output and standard error are redirected to the file postmaster.log within the data directory. There is no provision for rotating this file, so it will grow indefinitely unless server log output is redirected elsewhere by other settings. It is recommended that log_destination be set to syslog or that logging_collector be enabled when using this option. Even with those measures, errors reported early during startup may appear in postmaster.log rather than the normal log destination. When To Log client_min_messages (enum) client_min_messages configuration parameter Controls which message levels are sent to the client. Valid values are DEBUG5, DEBUG4, DEBUG3, DEBUG2, DEBUG1, LOG, NOTICE, WARNING, ERROR, FATAL, and PANIC. Each level includes all the levels that follow it. The later the level, the fewer messages are sent. The default is NOTICE. Note that LOG has a different rank here than in log_min_messages. log_min_messages (enum) log_min_messages configuration parameter Controls which message levels are written to the server log. Valid values are DEBUG5, DEBUG4, DEBUG3, DEBUG2, DEBUG1, INFO, NOTICE, WARNING, ERROR, LOG, FATAL, and PANIC. Each level includes all the levels that follow it. The later the level, the fewer messages are sent to the log. The default is WARNING. Note that LOG has a different rank here than in client_min_messages. Only superusers can change this setting. log_min_error_statement (enum) log_min_error_statement configuration parameter Controls which SQL statements that cause an error condition are recorded in the server log. The current SQL statement is included in the log entry for any message of the specified severity or higher. Valid values are DEBUG5, DEBUG4, DEBUG3, DEBUG2, DEBUG1, INFO, NOTICE, WARNING, ERROR, LOG, FATAL, and PANIC. The default is ERROR, which means statements causing errors, log messages, fatal errors, or panics will be logged. To effectively turn off logging of failing statements, set this parameter to PANIC. Only superusers can change this setting. log_min_duration_statement (integer) log_min_duration_statement configuration parameter Causes the duration of each completed statement to be logged if the statement ran for at least the specified number of milliseconds. Setting this to zero prints all statement durations. Minus-one (the default) disables logging statement durations. For example, if you set it to 250ms then all SQL statements that run 250ms or longer will be logged. Enabling this parameter can be helpful in tracking down unoptimized queries in your applications. Only superusers can change this setting. For clients using extended query protocol, durations of the Parse, Bind, and Execute steps are logged independently. When using this option together with , the text of statements that are logged because of log_statement will not be repeated in the duration log message. If you are not using syslog, it is recommended that you log the PID or session ID using so that you can link the statement message to the later duration message using the process ID or session ID. explains the message severity levels used by PostgreSQL. If logging output is sent to syslog or Windows' eventlog, the severity levels are translated as shown in the table. Message severity levels Severity Usage syslog eventlog DEBUG1..DEBUG5 Provides successively-more-detailed information for use by developers. DEBUG INFORMATION INFO Provides information implicitly requested by the user, e.g., output from VACUUM VERBOSE. INFO INFORMATION NOTICE Provides information that might be helpful to users, e.g., notice of truncation of long identifiers. NOTICE INFORMATION WARNING Provides warnings of likely problems, e.g., COMMIT outside a transaction block. NOTICE WARNING ERROR Reports an error that caused the current command to abort. WARNING ERROR LOG Reports information of interest to administrators, e.g., checkpoint activity. INFO INFORMATION FATAL Reports an error that caused the current session to abort. ERR ERROR PANIC Reports an error that caused all database sessions to abort. CRIT ERROR
What To Log application_name (string) application_name configuration parameter The application_name can be any string of less than NAMEDATALEN characters (64 characters in a standard build). It is typically set by an application upon connection to the server. The name will be displayed in the pg_stat_activity view and included in CSV log entries. It can also be included in regular log entries via the parameter. Only printable ASCII characters may be used in the application_name value. Other characters will be replaced with question marks (?). debug_print_parse (boolean) debug_print_rewritten (boolean) debug_print_plan (boolean) debug_print_parse configuration parameter debug_print_rewritten configuration parameter debug_print_plan configuration parameter These parameters enable various debugging output to be emitted. When set, they print the resulting parse tree, the query rewriter output, or the execution plan for each executed query. These messages are emitted at LOG message level, so by default they will appear in the server log but will not be sent to the client. You can change that by adjusting and/or . These parameters are off by default. debug_pretty_print (boolean) debug_pretty_print configuration parameter When set, debug_pretty_print indents the messages produced by debug_print_parse, debug_print_rewritten, or debug_print_plan. This results in more readable but much longer output than the compact format used when it is off. It is on by default. log_checkpoints (boolean) log_checkpoints configuration parameter Causes checkpoints to be logged in the server log. Some statistics about each checkpoint are included in the log messages, including the number of buffers written and the time spent writing them. This parameter can only be set in the postgresql.conf file or on the server command line. The default is off. log_connections (boolean) log_connections configuration parameter Causes each attempted connection to the server to be logged, as well as successful completion of client authentication. This parameter can only be set in the postgresql.conf file or on the server command line. The default is off. Some client programs, like psql, attempt to connect twice while determining if a password is required, so duplicate connection received messages do not necessarily indicate a problem. log_disconnections (boolean) log_disconnections configuration parameter This outputs a line in the server log similar to log_connections but at session termination, and includes the duration of the session. This is off by default. This parameter can only be set in the postgresql.conf file or on the server command line. log_duration (boolean) log_duration configuration parameter Causes the duration of every completed statement to be logged. The default is off. Only superusers can change this setting. For clients using extended query protocol, durations of the Parse, Bind, and Execute steps are logged independently. The difference between setting this option and setting to zero is that exceeding log_min_duration_statement forces the text of the query to be logged, but this option doesn't. Thus, if log_duration is on and log_min_duration_statement has a positive value, all durations are logged but the query text is included only for statements exceeding the threshold. This behavior can be useful for gathering statistics in high-load installations. log_error_verbosity (enum) log_error_verbosity configuration parameter Controls the amount of detail written in the server log for each message that is logged. Valid values are TERSE, DEFAULT, and VERBOSE, each adding more fields to displayed messages. TERSE excludes the logging of DETAIL, HINT, QUERY, and CONTEXT error information. VERBOSE output includes the SQLSTATE error code and the source code file name, function name, and line number that generated the error. Only superusers can change this setting. log_hostname (boolean) log_hostname configuration parameter By default, connection log messages only show the IP address of the connecting host. Turning this parameter on causes logging of the host name as well. Note that depending on your host name resolution setup this might impose a non-negligible performance penalty. This parameter can only be set in the postgresql.conf file or on the server command line. log_line_prefix (string) log_line_prefix configuration parameter This is a printf-style string that is output at the beginning of each log line. % characters begin escape sequences that are replaced with status information as outlined below. Unrecognized escapes are ignored. Other characters are copied straight to the log line. Some escapes are only recognized by session processes, and are ignored by background processes such as the main server process. This parameter can only be set in the postgresql.conf file or on the server command line. The default is an empty string. Escape Effect Session only %a Application name yes %u User name yes %d Database name yes %r Remote host name or IP address, and remote port yes %h Remote host name or IP address yes %p Process ID no %t Time stamp without milliseconds no %m Time stamp with milliseconds no %i Command tag: type of session's current command yes %e SQL state no %c Session ID: see below no %l Number of the log line for each session or process, starting at 1 no %s Process start time stamp no %v Virtual transaction ID (backendID/localXID) no %x Transaction ID (0 if none is assigned) no %q Produces no output, but tells non-session processes to stop at this point in the string; ignored by session processes no %% Literal % no The %c escape prints a quasi-unique session identifier, consisting of two 4-byte hexadecimal numbers (without leading zeros) separated by a dot. The numbers are the process start time and the process ID, so %c can also be used as a space saving way of printing those items. For example, to generate the session identifier from pg_stat_activity, use this query: SELECT to_hex(EXTRACT(EPOCH FROM backend_start)::integer) || '.' || to_hex(procpid) FROM pg_stat_activity; If you set a nonempty value for log_line_prefix, you should usually make its last character be a space, to provide visual separation from the rest of the log line. A punctuation character can be used too. Syslog produces its own time stamp and process ID information, so you probably do not want to use those escapes if you are logging to syslog. log_lock_waits (boolean) log_lock_waits configuration parameter Controls whether a log message is produced when a session waits longer than to acquire a lock. This is useful in determining if lock waits are causing poor performance. The default is off. log_statement (enum) log_statement configuration parameter Controls which SQL statements are logged. Valid values are none, ddl, mod, and all. ddl logs all data definition statements, such as CREATE, ALTER, and DROP statements. mod logs all ddl statements, plus data-modifying statements such as INSERT, UPDATE, DELETE, TRUNCATE, and COPY FROM. PREPARE, EXECUTE, and EXPLAIN ANALYZE statements are also logged if their contained command is of an appropriate type. For clients using extended query protocol, logging occurs when an Execute message is received, and values of the Bind parameters are included (with any embedded single-quote marks doubled). The default is none. Only superusers can change this setting. Statements that contain simple syntax errors are not logged even by the log_statement = all setting, because the log message is emitted only after basic parsing has been done to determine the statement type. In the case of extended query protocol, this setting likewise does not log statements that fail before the Execute phase (i.e., during parse analysis or planning). Set log_min_error_statement to ERROR (or lower) to log such statements. log_temp_files (integer) log_temp_files configuration parameter Controls logging of temporary file names and sizes. Temporary files can be created for sorts, hashes, and temporary query results. A log entry is made for each temporary file when it is deleted. A value of zero logs all temporary file information, while positive values log only files whose size is greater than or equal to the specified number of kilobytes. The default setting is -1, which disables such logging. Only superusers can change this setting. log_timezone (string) log_timezone configuration parameter Sets the time zone used for timestamps written in the log. Unlike , this value is cluster-wide, so that all sessions will report timestamps consistently. The default is unknown, which means use whatever the system environment specifies as the time zone. See for more information. This parameter can only be set in the postgresql.conf file or on the server command line. Using CSV-Format Log Output Including csvlog in the log_destination list provides a convenient way to import log files into a database table. This option emits log lines in comma-separated-values (CSV) format, with these columns: timestamp with milliseconds, user name, database name, process ID, client host:port number, session ID, per-session line number, command tag, session start time, virtual transaction ID, regular transaction ID, error severity, SQL state code, error message, error message detail, hint, internal query that led to the error (if any), character count of the error position therein, error context, user query that led to the error (if any and enabled by log_min_error_statement), character count of the error position therein, location of the error in the PostgreSQL source code (if log_error_verbosity is set to verbose), and application name. Here is a sample table definition for storing CSV-format log output: CREATE TABLE postgres_log ( log_time timestamp(3) with time zone, user_name text, database_name text, process_id integer, connection_from text, session_id text, session_line_num bigint, command_tag text, session_start_time timestamp with time zone, virtual_transaction_id text, transaction_id bigint, error_severity text, sql_state_code text, message text, detail text, hint text, internal_query text, internal_query_pos integer, context text, query text, query_pos integer, location text, application_name text, PRIMARY KEY (session_id, session_line_num) ); To import a log file into this table, use the COPY FROM command: COPY postgres_log FROM '/full/path/to/logfile.csv' WITH csv; There are a few things you need to do to simplify importing CSV log files: Set log_filename and log_rotation_age to provide a consistent, predictable naming scheme for your log files. This lets you predict what the file name will be and know when an individual log file is complete and therefore ready to be imported. Set log_rotation_size to 0 to disable size-based log rotation, as it makes the log file name difficult to predict. Set log_truncate_on_rotation to on so that old log data isn't mixed with the new in the same file. The table definition above includes a primary key specification. This is useful to protect against accidentally importing the same information twice. The COPY command commits all of the data it imports at one time, so any error will cause the entire import to fail. If you import a partial log file and later import the file again when it is complete, the primary key violation will cause the import to fail. Wait until the log is complete and closed before importing. This procedure will also protect against accidentally importing a partial line that hasn't been completely written, which would also cause COPY to fail.
Run-Time Statistics Query and Index Statistics Collector These parameters control server-wide statistics collection features. When statistics collection is enabled, the data that is produced can be accessed via the pg_stat and pg_statio family of system views. Refer to for more information. track_activities (boolean) track_activities configuration parameter Enables the collection of information on the currently executing command of each session, along with the time when that command began execution. This parameter is on by default. Note that even when enabled, this information is not visible to all users, only to superusers and the user owning the session being reported on, so it should not represent a security risk. Only superusers can change this setting. track_activity_query_size (integer) track_activity_query_size configuration parameter Specifies the number of bytes reserved to track the currently executing command for each active session, for the pg_stat_activity.current_query field. The default value is 1024. This parameter can only be set at server start. track_counts (boolean) track_counts configuration parameter Enables collection of statistics on database activity. This parameter is on by default, because the autovacuum daemon needs the collected information. Only superusers can change this setting. track_functions (enum) track_functions configuration parameter Enables tracking of function call counts and time used. Specify pl to track only procedural-language functions, all to also track SQL and C language functions. The default is none, which disables function statistics tracking. Only superusers can change this setting. SQL-language functions that are simple enough to be inlined into the calling query will not be tracked, regardless of this setting. update_process_title (boolean) update_process_title configuration parameter Enables updating of the process title every time a new SQL command is received by the server. The process title is typically viewed by the ps command, or in Windows by using the Process Explorer. Only superusers can change this setting. stats_temp_directory (string) stats_temp_directory configuration parameter Sets the directory to store temporary statistics data in. This can be a path relative to the data directory or an absolute path. The default is pg_stat_tmp. Pointing this at a RAM-based file system will decrease physical I/O requirements and can lead to improved performance. This parameter can only be set in the postgresql.conf file or on the server command line. Statistics Monitoring log_statement_stats (boolean) log_parser_stats (boolean) log_planner_stats (boolean) log_executor_stats (boolean) log_statement_stats configuration parameter log_parser_stats configuration parameter log_planner_stats configuration parameter log_executor_stats configuration parameter For each query, output performance statistics of the respective module to the server log. This is a crude profiling instrument, similar to the Unix getrusage() operating system facility. log_statement_stats reports total statement statistics, while the others report per-module statistics. log_statement_stats cannot be enabled together with any of the per-module options. All of these options are disabled by default. Only superusers can change these settings. Automatic Vacuuming autovacuum configuration parameters These settings control the behavior of the autovacuum feature. Refer to for more information. autovacuum (boolean) autovacuum configuration parameter Controls whether the server should run the autovacuum launcher daemon. This is on by default; however, must also be enabled for autovacuum to work. This parameter can only be set in the postgresql.conf file or on the server command line. Note that even when this parameter is disabled, the system will launch autovacuum processes if necessary to prevent transaction ID wraparound. See for more information. log_autovacuum_min_duration (integer) log_autovacuum_min_duration configuration parameter Causes each action executed by autovacuum to be logged if it ran for at least the specified number of milliseconds. Setting this to zero logs all autovacuum actions. Minus-one (the default) disables logging autovacuum actions. For example, if you set this to 250ms then all automatic vacuums and analyzes that run 250ms or longer will be logged. Enabling this parameter can be helpful in tracking autovacuum activity. This setting can only be set in the postgresql.conf file or on the server command line. autovacuum_max_workers (integer) autovacuum_max_workers configuration parameter Specifies the maximum number of autovacuum processes (other than the autovacuum launcher) which may be running at any one time. The default is three. This parameter can only be set at server start. autovacuum_naptime (integer) autovacuum_naptime configuration parameter Specifies the minimum delay between autovacuum runs on any given database. In each round the daemon examines the database and issues VACUUM and ANALYZE commands as needed for tables in that database. The delay is measured in seconds, and the default is one minute (1min). This parameter can only be set in the postgresql.conf file or on the server command line. autovacuum_vacuum_threshold (integer) autovacuum_vacuum_threshold configuration parameter Specifies the minimum number of updated or deleted tuples needed to trigger a VACUUM in any one table. The default is 50 tuples. This parameter can only be set in the postgresql.conf file or on the server command line. This setting can be overridden for individual tables by changing storage parameters. autovacuum_analyze_threshold (integer) autovacuum_analyze_threshold configuration parameter Specifies the minimum number of inserted, updated or deleted tuples needed to trigger an ANALYZE in any one table. The default is 50 tuples. This parameter can only be set in the postgresql.conf file or on the server command line. This setting can be overridden for individual tables by changing storage parameters. autovacuum_vacuum_scale_factor (floating point) autovacuum_vacuum_scale_factor configuration parameter Specifies a fraction of the table size to add to autovacuum_vacuum_threshold when deciding whether to trigger a VACUUM. The default is 0.2 (20% of table size). This parameter can only be set in the postgresql.conf file or on the server command line. This setting can be overridden for individual tables by changing storage parameters. autovacuum_analyze_scale_factor (floating point) autovacuum_analyze_scale_factor configuration parameter Specifies a fraction of the table size to add to autovacuum_analyze_threshold when deciding whether to trigger an ANALYZE. The default is 0.1 (10% of table size). This parameter can only be set in the postgresql.conf file or on the server command line. This setting can be overridden for individual tables by changing storage parameters. autovacuum_freeze_max_age (integer) autovacuum_freeze_max_age configuration parameter Specifies the maximum age (in transactions) that a table's pg_class.relfrozenxid field can attain before a VACUUM operation is forced to prevent transaction ID wraparound within the table. Note that the system will launch autovacuum processes to prevent wraparound even when autovacuum is otherwise disabled. The default is 200 million transactions. This parameter can only be set at server start, but the setting can be reduced for individual tables by changing storage parameters. For more information see . autovacuum_vacuum_cost_delay (integer) autovacuum_vacuum_cost_delay configuration parameter Specifies the cost delay value that will be used in automatic VACUUM operations. If -1 is specified, the regular value will be used. The default value is 20 milliseconds. This parameter can only be set in the postgresql.conf file or on the server command line. This setting can be overridden for individual tables by changing storage parameters. autovacuum_vacuum_cost_limit (integer) autovacuum_vacuum_cost_limit configuration parameter Specifies the cost limit value that will be used in automatic VACUUM operations. If -1 is specified (which is the default), the regular value will be used. Note that the value is distributed proportionally among the running autovacuum workers, if there is more than one, so that the sum of the limits of each worker never exceeds the limit on this variable. This parameter can only be set in the postgresql.conf file or on the server command line. This setting can be overridden for individual tables by changing storage parameters. Client Connection Defaults Statement Behavior search_path (string) search_path configuration parameter pathfor schemas This variable specifies the order in which schemas are searched when an object (table, data type, function, etc.) is referenced by a simple name with no schema specified. When there are objects of identical names in different schemas, the one found first in the search path is used. An object that is not in any of the schemas in the search path can only be referenced by specifying its containing schema with a qualified (dotted) name. The value for search_path must be a comma-separated list of schema names. If one of the list items is the special value $user, then the schema having the name returned by SESSION_USER is substituted, if there is such a schema. (If not, $user is ignored.) The system catalog schema, pg_catalog, is always searched, whether it is mentioned in the path or not. If it is mentioned in the path then it will be searched in the specified order. If pg_catalog is not in the path then it will be searched before searching any of the path items. Likewise, the current session's temporary-table schema, pg_temp_nnn, is always searched if it exists. It can be explicitly listed in the path by using the alias pg_temp. If it is not listed in the path then it is searched first (even before pg_catalog). However, the temporary schema is only searched for relation (table, view, sequence, etc) and data type names. It is never searched for function or operator names. When objects are created without specifying a particular target schema, they will be placed in the first schema listed in the search path. An error is reported if the search path is empty. The default value for this parameter is '"$user", public' (where the second part will be ignored if there is no schema named public). This supports shared use of a database (where no users have private schemas, and all share use of public), private per-user schemas, and combinations of these. Other effects can be obtained by altering the default search path setting, either globally or per-user. The current effective value of the search path can be examined via the SQL function current_schemas(). This is not quite the same as examining the value of search_path, since current_schemas() shows how the items appearing in search_path were resolved. For more information on schema handling, see . default_tablespace (string) default_tablespace configuration parameter tablespacedefault This variable specifies the default tablespace in which to create objects (tables and indexes) when a CREATE command does not explicitly specify a tablespace. The value is either the name of a tablespace, or an empty string to specify using the default tablespace of the current database. If the value does not match the name of any existing tablespace, PostgreSQL will automatically use the default tablespace of the current database. If a nondefault tablespace is specified, the user must have CREATE privilege for it, or creation attempts will fail. This variable is not used for temporary tables; for them, is consulted instead. For more information on tablespaces, see . temp_tablespaces (string) temp_tablespaces configuration parameter tablespacetemporary This variable specifies tablespaces in which to create temporary objects (temp tables and indexes on temp tables) when a CREATE command does not explicitly specify a tablespace. Temporary files for purposes such as sorting large data sets are also created in these tablespaces. The value is a list of names of tablespaces. When there is more than one name in the list, PostgreSQL chooses a random member of the list each time a temporary object is to be created; except that within a transaction, successively created temporary objects are placed in successive tablespaces from the list. If the selected element of the list is an empty string, PostgreSQL will automatically use the default tablespace of the current database instead. When temp_tablespaces is set interactively, specifying a nonexistent tablespace is an error, as is specifying a tablespace for which the user does not have CREATE privilege. However, when using a previously set value, nonexistent tablespaces are ignored, as are tablespaces for which the user lacks CREATE privilege. In particular, this rule applies when using a value set in postgresql.conf. The default value is an empty string, which results in all temporary objects being created in the default tablespace of the current database. See also . check_function_bodies (boolean) check_function_bodies configuration parameter This parameter is normally on. When set to off, it disables validation of the function body string during . Disabling validation is occasionally useful to avoid problems such as forward references when restoring function definitions from a dump. transaction isolation level default_transaction_isolation configuration parameter default_transaction_isolation (enum) Each SQL transaction has an isolation level, which can be either read uncommitted, read committed, repeatable read, or serializable. This parameter controls the default isolation level of each new transaction. The default is read committed. Consult and for more information. read-only transaction default_transaction_read_only configuration parameter default_transaction_read_only (boolean) A read-only SQL transaction cannot alter non-temporary tables. This parameter controls the default read-only status of each new transaction. The default is off (read/write). Consult for more information. session_replication_role (enum) session_replication_role configuration parameter Controls firing of replication-related triggers and rules for the current session. Setting this variable requires superuser privilege and results in discarding any previously cached query plans. Possible values are origin (the default), replica and local. See for more information. statement_timeout (integer) statement_timeout configuration parameter Abort any statement that takes over the specified number of milliseconds, starting from the time the command arrives at the server from the client. If log_min_error_statement is set to ERROR or lower, the statement that timed out will also be logged. A value of zero (the default) turns this off. Setting statement_timeout in postgresql.conf is not recommended because it affects all sessions. vacuum_freeze_table_age (integer) vacuum_freeze_table_age configuration parameter VACUUM performs a whole-table scan if the table's pg_class.relfrozenxid field has reached the age specified by this setting. The default is 150 million transactions. Although users can set this value anywhere from zero to one billion, VACUUM will silently limit the effective value to 95% of , so that a periodical manual VACUUM has a chance to run before an anti-wraparound autovacuum is launched for the table. For more information see . vacuum_freeze_min_age (integer) vacuum_freeze_min_age configuration parameter Specifies the cutoff age (in transactions) that VACUUM should use to decide whether to replace transaction IDs with FrozenXID while scanning a table. The default is 50 million transactions. Although users can set this value anywhere from zero to one billion, VACUUM will silently limit the effective value to half the value of , so that there is not an unreasonably short time between forced autovacuums. For more information see . vacuum_defer_cleanup_age (integer) vacuum_defer_cleanup_age configuration parameter Specifies the number of transactions by which VACUUM and HOT updates will defer cleanup of dead row versions. The default is 0 transactions, meaning that dead row versions will be removed as soon as possible. You may wish to set this to a non-zero value when planning or maintaining a configuration. The recommended value is 0 unless you have clear reason to increase it. The purpose of the parameter is to allow the user to specify an approximate time delay before cleanup occurs. However, it should be noted that there is no direct link with any specific time delay and so the results will be application and installation specific, as well as variable over time, depending upon the transaction rate (of writes only). bytea_output (enum) bytea_output configuration parameter Sets the output format for values of type bytea. Valid values are hex (the default) and escape (the traditional PostgreSQL format). See for more information. The bytea type always accepts both formats on input, regardless of this setting. xmlbinary (enum) xmlbinary configuration parameter Sets how binary values are to be encoded in XML. This applies for example when bytea values are converted to XML by the functions xmlelement or xmlforest. Possible values are base64 and hex, which are both defined in the XML Schema standard. The default is base64. For further information about XML-related functions, see . The actual choice here is mostly a matter of taste, constrained only by possible restrictions in client applications. Both methods support all possible values, although the hex encoding will be somewhat larger than the base64 encoding. xmloption (enum) xmloption configuration parameter SET XML OPTION XML option Sets whether DOCUMENT or CONTENT is implicit when converting between XML and character string values. See for a description of this. Valid values are DOCUMENT and CONTENT. The default is CONTENT. According to the SQL standard, the command to set this option is SET XML OPTION { DOCUMENT | CONTENT }; This syntax is also available in PostgreSQL. Locale and Formatting DateStyle (string) DateStyle configuration parameter Sets the display format for date and time values, as well as the rules for interpreting ambiguous date input values. For historical reasons, this variable contains two independent components: the output format specification (ISO, Postgres, SQL, or German) and the input/output specification for year/month/day ordering (DMY, MDY, or YMD). These can be set separately or together. The keywords Euro and European are synonyms for DMY; the keywords US, NonEuro, and NonEuropean are synonyms for MDY. See for more information. The built-in default is ISO, MDY, but initdb will initialize the configuration file with a setting that corresponds to the behavior of the chosen lc_time locale. IntervalStyle (enum) IntervalStyle configuration parameter Sets the display format for interval values. The value sql_standard will produce output matching SQL standard interval literals. The value postgres (which is the default) will produce output matching PostgreSQL releases prior to 8.4 when the parameter was set to ISO. The value postgres_verbose will produce output matching PostgreSQL releases prior to 8.4 when the DateStyle parameter was set to non-ISO output. The value iso_8601 will produce output matching the time interval format with designators defined in section 4.4.3.2 of ISO 8601. The IntervalStyle parameter also affects the interpretation of ambiguous interval input. See for more information. timezone (string) timezone configuration parameter time zone Sets the time zone for displaying and interpreting time stamps. The default is unknown, which means to use whatever the system environment specifies as the time zone. See for more information. timezone_abbreviations (string) timezone_abbreviations configuration parameter time zone names Sets the collection of time zone abbreviations that will be accepted by the server for datetime input. The default is 'Default', which is a collection that works in most of the world; there are also 'Australia' and 'India', and other collections can be defined for a particular installation. See for more information. significant digits floating-point display extra_float_digits configuration parameter extra_float_digits (integer) This parameter adjusts the number of digits displayed for floating-point values, including float4, float8, and geometric data types. The parameter value is added to the standard number of digits (FLT_DIG or DBL_DIG as appropriate). The value can be set as high as 3, to include partially-significant digits; this is especially useful for dumping float data that needs to be restored exactly. Or it can be set negative to suppress unwanted digits. client_encoding (string) client_encoding configuration parameter character set Sets the client-side encoding (character set). The default is to use the database encoding. lc_messages (string) lc_messages configuration parameter Sets the language in which messages are displayed. Acceptable values are system-dependent; see for more information. If this variable is set to the empty string (which is the default) then the value is inherited from the execution environment of the server in a system-dependent way. On some systems, this locale category does not exist. Setting this variable will still work, but there will be no effect. Also, there is a chance that no translated messages for the desired language exist. In that case you will continue to see the English messages. Only superusers can change this setting, because it affects the messages sent to the server log as well as to the client, and an improper value might obscure the readability of the server logs. lc_monetary (string) lc_monetary configuration parameter Sets the locale to use for formatting monetary amounts, for example with the to_char family of functions. Acceptable values are system-dependent; see for more information. If this variable is set to the empty string (which is the default) then the value is inherited from the execution environment of the server in a system-dependent way. lc_numeric (string) lc_numeric configuration parameter Sets the locale to use for formatting numbers, for example with the to_char family of functions. Acceptable values are system-dependent; see for more information. If this variable is set to the empty string (which is the default) then the value is inherited from the execution environment of the server in a system-dependent way. lc_time (string) lc_time configuration parameter Sets the locale to use for formatting dates and times, for example with the to_char family of functions. Acceptable values are system-dependent; see for more information. If this variable is set to the empty string (which is the default) then the value is inherited from the execution environment of the server in a system-dependent way. default_text_search_config (string) default_text_search_config configuration parameter Selects the text search configuration that is used by those variants of the text search functions that do not have an explicit argument specifying the configuration. See for further information. The built-in default is pg_catalog.simple, but initdb will initialize the configuration file with a setting that corresponds to the chosen lc_ctype locale, if a configuration matching that locale can be identified. Other Defaults dynamic_library_path (string) dynamic_library_path configuration parameter dynamic loading If a dynamically loadable module needs to be opened and the file name specified in the CREATE FUNCTION or LOAD command does not have a directory component (i.e., the name does not contain a slash), the system will search this path for the required file. The value for dynamic_library_path must be a list of absolute directory paths separated by colons (or semi-colons on Windows). If a list element starts with the special string $libdir, the compiled-in PostgreSQL package library directory is substituted for $libdir; this is where the modules provided by the standard PostgreSQL distribution are installed. (Use pg_config --pkglibdir to find out the name of this directory.) For example: dynamic_library_path = '/usr/local/lib/postgresql:/home/my_project/lib:$libdir' or, in a Windows environment: dynamic_library_path = 'C:\tools\postgresql;H:\my_project\lib;$libdir' The default value for this parameter is '$libdir'. If the value is set to an empty string, the automatic path search is turned off. This parameter can be changed at run time by superusers, but a setting done that way will only persist until the end of the client connection, so this method should be reserved for development purposes. The recommended way to set this parameter is in the postgresql.conf configuration file. gin_fuzzy_search_limit (integer) gin_fuzzy_search_limit configuration parameter Soft upper limit of the size of the set returned by GIN index scans. For more information see . local_preload_libraries (string) local_preload_libraries configuration parameter $libdir/plugins This variable specifies one or more shared libraries that are to be preloaded at connection start. If more than one library is to be loaded, separate their names with commas. This parameter cannot be changed after the start of a particular session. Because this is not a superuser-only option, the libraries that can be loaded are restricted to those appearing in the plugins subdirectory of the installation's standard library directory. (It is the database administrator's responsibility to ensure that only safe libraries are installed there.) Entries in local_preload_libraries can specify this directory explicitly, for example $libdir/plugins/mylib, or just specify the library name — mylib would have the same effect as $libdir/plugins/mylib. Unlike local_preload_libraries, there is no performance advantage to loading a library at session start rather than when it is first used. Rather, the intent of this feature is to allow debugging or performance-measurement libraries to be loaded into specific sessions without an explicit LOAD command being given. For example, debugging could be enabled for all sessions under a given user name by setting this parameter with ALTER USER SET. If a specified library is not found, the connection attempt will fail. Every PostgreSQL-supported library has a magic block that is checked to guarantee compatibility. For this reason, non-PostgreSQL libraries cannot be loaded in this way. Lock Management deadlock timeout during timeout deadlock deadlock_timeout configuration parameter deadlock_timeout (integer) This is the amount of time, in milliseconds, to wait on a lock before checking to see if there is a deadlock condition. The check for deadlock is relatively expensive, so the server doesn't run it every time it waits for a lock. We optimistically assume that deadlocks are not common in production applications and just wait on the lock for a while before checking for a deadlock. Increasing this value reduces the amount of time wasted in needless deadlock checks, but slows down reporting of real deadlock errors. The default is one second (1s), which is probably about the smallest value you would want in practice. On a heavily loaded server you might want to raise it. Ideally the setting should exceed your typical transaction time, so as to improve the odds that a lock will be released before the waiter decides to check for deadlock. When is set, this parameter also determines the length of time to wait before a log message is issued about the lock wait. If you are trying to investigate locking delays you might want to set a shorter than normal deadlock_timeout. max_locks_per_transaction (integer) max_locks_per_transaction configuration parameter The shared lock table tracks locks on max_locks_per_transaction * ( + ) objects (e.g., tables); hence, no more than this many distinct objects can be locked at any one time. This parameter controls the average number of object locks allocated for each transaction; individual transactions can lock more objects as long as the locks of all transactions fit in the lock table. This is not the number of rows that can be locked; that value is unlimited. The default, 64, has historically proven sufficient, but you might need to raise this value if you have clients that touch many different tables in a single transaction. This parameter can only be set at server start. Increasing this parameter might cause PostgreSQL to request more System V shared memory than your operating system's default configuration allows. See for information on how to adjust those parameters, if necessary. When running a standby server, you must set this parameter to the same or higher value than on the master server. Otherwise, queries will not be allowed in the standby server. Version and Platform Compatibility Previous PostgreSQL Versions array_nulls (boolean) array_nulls configuration parameter This controls whether the array input parser recognizes unquoted NULL as specifying a null array element. By default, this is on, allowing array values containing null values to be entered. However, PostgreSQL versions before 8.2 did not support null values in arrays, and therefore would treat NULL as specifying a normal array element with the string value NULL. For backwards compatibility with applications that require the old behavior, this variable can be turned off. Note that it is possible to create array values containing null values even when this variable is off. backslash_quote (enum) stringsbackslash quotes backslash_quote configuration parameter This controls whether a quote mark can be represented by \' in a string literal. The preferred, SQL-standard way to represent a quote mark is by doubling it ('') but PostgreSQL has historically also accepted \'. However, use of \' creates security risks because in some client character set encodings, there are multibyte characters in which the last byte is numerically equivalent to ASCII \. If client-side code does escaping incorrectly then a SQL-injection attack is possible. This risk can be prevented by making the server reject queries in which a quote mark appears to be escaped by a backslash. The allowed values of backslash_quote are on (allow \' always), off (reject always), and safe_encoding (allow only if client encoding does not allow ASCII \ within a multibyte character). safe_encoding is the default setting. Note that in a standard-conforming string literal, \ just means \ anyway. This parameter only affects the handling of non-standard-conforming literals, including escape string syntax (E'...'). default_with_oids (boolean) default_with_oids configuration parameter This controls whether CREATE TABLE and CREATE TABLE AS include an OID column in newly-created tables, if neither WITH OIDS nor WITHOUT OIDS is specified. It also determines whether OIDs will be included in tables created by SELECT INTO. The parameter is off by default; in PostgreSQL 8.0 and earlier, it was on by default. The use of OIDs in user tables is considered deprecated, so most installations should leave this variable disabled. Applications that require OIDs for a particular table should specify WITH OIDS when creating the table. This variable can be enabled for compatibility with old applications that do not follow this behavior. escape_string_warning (boolean) stringsescape warning escape_string_warning configuration parameter When on, a warning is issued if a backslash (\) appears in an ordinary string literal ('...' syntax) and standard_conforming_strings is off. The default is on. Applications that wish to use backslash as escape should be modified to use escape string syntax (E'...'), because the default behavior of ordinary strings will change in a future release for SQL compatibility. This variable can be enabled to help detect applications that will break. lo_compat_privileges (boolean) lo_compat_privileges configuration parameter In PostgreSQL releases prior to 8.5, large objects did not have access privileges and were, in effect, readable and writable by all users. Setting this variable to on disables the new privilege checks, for compatibility with prior releases. The default is off. Setting this variable does not disable all security checks for large objects - only those for which the default behavior has changed in PostgreSQL 8.5. For example, lo_import() and lo_export() need superuser privileges independent of this setting. sql_inheritance (boolean) sql_inheritance configuration parameter inheritance This controls the inheritance semantics. If turned off, subtables are not accessed by various commands by default; basically an implied ONLY key word. This was added for compatibility with releases prior to 7.1. See for more information. standard_conforming_strings (boolean) stringsstandard conforming standard_conforming_strings configuration parameter This controls whether ordinary string literals ('...') treat backslashes literally, as specified in the SQL standard. The default is currently off, causing PostgreSQL to have its historical behavior of treating backslashes as escape characters. The default will change to on in a future release to improve compatibility with the SQL standard. Applications can check this parameter to determine how string literals will be processed. The presence of this parameter can also be taken as an indication that the escape string syntax (E'...') is supported. Escape string syntax () should be used if an application desires backslashes to be treated as escape characters. synchronize_seqscans (boolean) synchronize_seqscans configuration parameter This allows sequential scans of large tables to synchronize with each other, so that concurrent scans read the same block at about the same time and hence share the I/O workload. When this is enabled, a scan might start in the middle of the table and then wrap around the end to cover all rows, so as to synchronize with the activity of scans already in progress. This can result in unpredictable changes in the row ordering returned by queries that have no ORDER BY clause. Setting this parameter to off ensures the pre-8.3 behavior in which a sequential scan always starts from the beginning of the table. The default is on. Platform and Client Compatibility transform_null_equals (boolean) IS NULL transform_null_equals configuration parameter When on, expressions of the form expr = NULL (or NULL = expr) are treated as expr IS NULL, that is, they return true if expr evaluates to the null value, and false otherwise. The correct SQL-spec-compliant behavior of expr = NULL is to always return null (unknown). Therefore this parameter defaults to off. However, filtered forms in Microsoft Access generate queries that appear to use expr = NULL to test for null values, so if you use that interface to access the database you might want to turn this option on. Since expressions of the form expr = NULL always return the null value (using the SQL standard interpretation), they are not very useful and do not appear often in normal applications so this option does little harm in practice. But new users are frequently confused about the semantics of expressions involving null values, so this option is off by default. Note that this option only affects the exact form = NULL, not other comparison operators or other expressions that are computationally equivalent to some expression involving the equals operator (such as IN). Thus, this option is not a general fix for bad programming. Refer to for related information. Preset Options The following parameters are read-only, and are determined when PostgreSQL is compiled or when it is installed. As such, they have been excluded from the sample postgresql.conf file. These options report various aspects of PostgreSQL behavior that might be of interest to certain applications, particularly administrative front-ends. block_size (integer) block_size configuration parameter Reports the size of a disk block. It is determined by the value of BLCKSZ when building the server. The default value is 8192 bytes. The meaning of some configuration variables (such as ) is influenced by block_size. See for information. integer_datetimes (boolean) integer_datetimes configuration parameter Reports whether PostgreSQL was built with support for 64-bit-integer dates and times. This can be disabled by configuring with --disable-integer-datetimes when building PostgreSQL. The default value is on. lc_collate (string) lc_collate configuration parameter Reports the locale in which sorting of textual data is done. See for more information. This value is determined when a database is created. lc_ctype (string) lc_ctype configuration parameter Reports the locale that determines character classifications. See for more information. This value is determined when a database is created. Ordinarily this will be the same as lc_collate, but for special applications it might be set differently. max_function_args (integer) max_function_args configuration parameter Reports the maximum number of function arguments. It is determined by the value of FUNC_MAX_ARGS when building the server. The default value is 100 arguments. max_identifier_length (integer) max_identifier_length configuration parameter Reports the maximum identifier length. It is determined as one less than the value of NAMEDATALEN when building the server. The default value of NAMEDATALEN is 64; therefore the default max_identifier_length is 63 bytes, which can be less than 63 characters when using multi-byte encodings. max_index_keys (integer) max_index_keys configuration parameter Reports the maximum number of index keys. It is determined by the value of INDEX_MAX_KEYS when building the server. The default value is 32 keys. segment_size (integer) segment_size configuration parameter Reports the number of blocks (pages) that can be stored within a file segment. It is determined by the value of RELSEG_SIZE when building the server. The maximum size of a segment file in bytes is equal to segment_size multiplied by block_size; by default this is 1GB. server_encoding (string) server_encoding configuration parameter character set Reports the database encoding (character set). It is determined when the database is created. Ordinarily, clients need only be concerned with the value of . server_version (string) server_version configuration parameter Reports the version number of the server. It is determined by the value of PG_VERSION when building the server. server_version_num (integer) server_version_num configuration parameter Reports the version number of the server as an integer. It is determined by the value of PG_VERSION_NUM when building the server. wal_block_size (integer) wal_block_size configuration parameter Reports the size of a WAL disk block. It is determined by the value of XLOG_BLCKSZ when building the server. The default value is 8192 bytes. wal_segment_size (integer) wal_segment_size configuration parameter Reports the number of blocks (pages) in a WAL segment file. The total size of a WAL segment file in bytes is equal to wal_segment_size multiplied by wal_block_size; by default this is 16MB. See for more information. Customized Options This feature was designed to allow parameters not normally known to PostgreSQL to be added by add-on modules (such as procedural languages). This allows add-on modules to be configured in the standard ways. custom_variable_classes (string) custom_variable_classes configuration parameter This variable specifies one or several class names to be used for custom variables, in the form of a comma-separated list. A custom variable is a variable not normally known to PostgreSQL proper but used by some add-on module. Such variables must have names consisting of a class name, a dot, and a variable name. custom_variable_classes specifies all the class names in use in a particular installation. This parameter can only be set in the postgresql.conf file or on the server command line. The difficulty with setting custom variables in postgresql.conf is that the file must be read before add-on modules have been loaded, and so custom variables would ordinarily be rejected as unknown. When custom_variable_classes is set, the server will accept definitions of arbitrary variables within each specified class. These variables will be treated as placeholders and will have no function until the module that defines them is loaded. When a module for a specific class is loaded, it will add the proper variable definitions for its class name, convert any placeholder values according to those definitions, and issue warnings for any unrecognized placeholders of its class that remain. Here is an example of what postgresql.conf might contain when using custom variables: custom_variable_classes = 'plpgsql,plperl' plpgsql.variable_conflict = use_variable plperl.use_strict = true plruby.use_strict = true # generates error: unknown class name Developer Options The following parameters are intended for work on the PostgreSQL source code, and in some cases to assist with recovery of severely damaged databases. There should be no reason to use them on a production database. As such, they have been excluded from the sample postgresql.conf file. Note that many of these parameters require special source compilation flags to work at all. allow_system_table_mods (boolean) allow_system_table_mods configuration parameter Allows modification of the structure of system tables. This is used by initdb. This parameter can only be set at server start. debug_assertions (boolean) debug_assertions configuration parameter Turns on various assertion checks. This is a debugging aid. If you are experiencing strange problems or crashes you might want to turn this on, as it might expose programming mistakes. To use this parameter, the macro USE_ASSERT_CHECKING must be defined when PostgreSQL is built (accomplished by the configure option ). Note that debug_assertions defaults to on if PostgreSQL has been built with assertions enabled. ignore_system_indexes (boolean) ignore_system_indexes configuration parameter Ignore system indexes when reading system tables (but still update the indexes when modifying the tables). This is useful when recovering from damaged system indexes. This parameter cannot be changed after session start. post_auth_delay (integer) post_auth_delay configuration parameter If nonzero, a delay of this many seconds occurs when a new server process is started, after it conducts the authentication procedure. This is intended to give developers an opportunity to attach to the server process with a debugger. This parameter cannot be changed after session start. pre_auth_delay (integer) pre_auth_delay configuration parameter If nonzero, a delay of this many seconds occurs just after a new server process is forked, before it conducts the authentication procedure. This is intended to give developers an opportunity to attach to the server process with a debugger to trace down misbehavior in authentication. This parameter can only be set in the postgresql.conf file or on the server command line. trace_notify (boolean) trace_notify configuration parameter Generates a great amount of debugging output for the LISTEN and NOTIFY commands. or must be DEBUG1 or lower to send this output to the client or server logs, respectively. trace_sort (boolean) trace_sort configuration parameter If on, emit information about resource usage during sort operations. This parameter is only available if the TRACE_SORT macro was defined when PostgreSQL was compiled. (However, TRACE_SORT is currently defined by default.) trace_locks (boolean) trace_locks configuration parameter If on, emit information about lock usage. Information dumped includes the type of lock operation, the type of lock and the unique identifier of the object being locked or unlocked. Also included are bitmasks for the lock types already granted on this object as well as for the lock types awaited on this object. For each lock type a count of the number of granted locks and waiting locks is also dumped as well as the totals. An example of the log file output is shown here: LOG: LockAcquire: new: lock(0xb7acd844) id(24688,24696,0,0,0,1) grantMask(0) req(0,0,0,0,0,0,0)=0 grant(0,0,0,0,0,0,0)=0 wait(0) type(AccessShareLock) LOG: GrantLock: lock(0xb7acd844) id(24688,24696,0,0,0,1) grantMask(2) req(1,0,0,0,0,0,0)=1 grant(1,0,0,0,0,0,0)=1 wait(0) type(AccessShareLock) LOG: UnGrantLock: updated: lock(0xb7acd844) id(24688,24696,0,0,0,1) grantMask(0) req(0,0,0,0,0,0,0)=0 grant(0,0,0,0,0,0,0)=0 wait(0) type(AccessShareLock) LOG: CleanUpLock: deleting: lock(0xb7acd844) id(24688,24696,0,0,0,1) grantMask(0) req(0,0,0,0,0,0,0)=0 grant(0,0,0,0,0,0,0)=0 wait(0) type(INVALID) Details of the structure being dumped may be found in src/include/storage/lock.h This parameter is only available if the LOCK_DEBUG macro was defined when PostgreSQL was compiled. trace_lwlocks (boolean) trace_lwlocks configuration parameter If on, emit information about lightweight lock usage. Lightweight locks are intended primarily to provide mutual exclusion of access to shared-memory data structures. This parameter is only available if the LOCK_DEBUG macro was defined when PostgreSQL was compiled. trace_userlocks (boolean) trace_userlocks configuration parameter If on, emit information about user lock usage. Output is the same as for trace_locks, only for user locks. User locks were removed as of PostgreSQL version 8.2. This option currently has no effect. This parameter is only available if the LOCK_DEBUG macro was defined when PostgreSQL was compiled. trace_lock_oidmin (integer) trace_lock_oidmin configuration parameter If set, do not trace locks for tables below this OID. (use to avoid output on system tables) This parameter is only available if the LOCK_DEBUG macro was defined when PostgreSQL was compiled. trace_lock_table (integer) trace_lock_table configuration parameter Unconditionally trace locks on this table (OID). This parameter is only available if the LOCK_DEBUG macro was defined when PostgreSQL was compiled. debug_deadlocks (boolean) debug_deadlocks configuration parameter If set, dumps information about all current locks when a DeadLockTimeout occurs. This parameter is only available if the LOCK_DEBUG macro was defined when PostgreSQL was compiled. log_btree_build_stats (boolean) log_btree_build_stats configuration parameter If set, logs system resource usage statistics (memory and CPU) on various btree operations. This parameter is only available if the BTREE_BUILD_STATS macro was defined when PostgreSQL was compiled. wal_debug (boolean) wal_debug configuration parameter If on, emit WAL-related debugging output. This parameter is only available if the WAL_DEBUG macro was defined when PostgreSQL was compiled. trace_recovery_messages (string) trace_recovery_messages configuration parameter Controls which message levels are written to the server log for system modules needed for recovery processing. This allows the user to override the normal setting of log_min_messages, but only for specific messages. This is intended for use in debugging Hot Standby. Valid values are DEBUG5, DEBUG4, DEBUG3, DEBUG2, DEBUG1, INFO, NOTICE, WARNING, ERROR, LOG, FATAL, and PANIC. Each level includes all the levels that follow it. The later the level, the fewer messages are sent to the log. The default is WARNING. Note that LOG has a different rank here than in client_min_messages. Parameter should be set in the postgresql.conf only. zero_damaged_pages (boolean) zero_damaged_pages configuration parameter Detection of a damaged page header normally causes PostgreSQL to report an error, aborting the current command. Setting zero_damaged_pages to on causes the system to instead report a warning, zero out the damaged page, and continue processing. This behavior will destroy data, namely all the rows on the damaged page. But it allows you to get past the error and retrieve rows from any undamaged pages that might be present in the table. So it is useful for recovering data if corruption has occurred due to a hardware or software error. You should generally not set this on until you have given up hope of recovering data from the damaged pages of a table. The default setting is off, and it can only be changed by a superuser. Short Options For convenience there are also single letter command-line option switches available for some parameters. They are described in . Some of these options exist for historical reasons, and their presence as a single-letter option does not necessarily indicate an endorsement to use the option heavily. Short option key Short option Equivalent debug_assertions = x shared_buffers = x log_min_messages = DEBUGx datestyle = euro , , , , , , enable_bitmapscan = off, enable_hashjoin = off, enable_indexscan = off, enable_mergejoin = off, enable_nestloop = off, enable_seqscan = off, enable_tidscan = off fsync = off listen_addresses = x listen_addresses = '*' unix_socket_directory = x ssl = on max_connections = x allow_system_table_mods = on port = x ignore_system_indexes = on log_statement_stats = on work_mem = x , , log_parser_stats = on, log_planner_stats = on, log_executor_stats = on post_auth_delay = x