<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.postgresql.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Natmaka</id>
	<title>PostgreSQL wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.postgresql.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Natmaka"/>
	<link rel="alternate" type="text/html" href="https://wiki.postgresql.org/wiki/Special:Contributions/Natmaka"/>
	<updated>2026-06-10T00:37:00Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.39.17</generator>
	<entry>
		<id>https://wiki.postgresql.org/index.php?title=Tuning_Your_PostgreSQL_Server&amp;diff=24684</id>
		<title>Tuning Your PostgreSQL Server</title>
		<link rel="alternate" type="text/html" href="https://wiki.postgresql.org/index.php?title=Tuning_Your_PostgreSQL_Server&amp;diff=24684"/>
		<updated>2015-05-16T13:14:48Z</updated>

		<summary type="html">&lt;p&gt;Natmaka: /* random_page_cost */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;__NOTOC__&lt;br /&gt;
&#039;&#039;by Greg Smith, Robert Treat, and Christopher Browne&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
{{Languages}}&lt;br /&gt;
&lt;br /&gt;
PostgreSQL ships with a basic configuration tuned for wide compatibility rather than performance. Odds are good the default parameters are very undersized for your system. Rather than get dragged into the details of everything you should eventually know (which you can find if you want it at the [http://www.pgcon.org/2008/schedule/events/104.en.html GUC Three Hour Tour]), here we&#039;re going to sprint through a simplified view of the basics, with a look at the most common things people new to PostgreSQL aren&#039;t aware of.  You should click on the name of the parameter in each section to jump to the relevant documentation in the PostgreSQL manual for more details after reading the quick intro here.  There is also additional information available about many of these parameters, as well as a list of parameters you shouldn&#039;t adjust, at [https://www.packtpub.com/article/server-configuration-tuning-postgresql Server Configuration Tuning].&lt;br /&gt;
&lt;br /&gt;
== Background Information on Configuration Settings ==&lt;br /&gt;
&lt;br /&gt;
PostgreSQL settings can be manipulated a number of different ways, but generally you will want them changed in your configuration files, either directly or, starting with PostgreSQL 9.4, through [http://www.postgresql.org/docs/current/static/sql-altersystem.html &amp;lt;tt&amp;gt;ALTER SYSTEM&amp;lt;/tt&amp;gt;]. The specific options available change from release to release, the definitive list is in the source code at src/backend/utils/misc/guc.c for your version of PostgreSQL (but the pg_settings view works well enough for most purposes).&lt;br /&gt;
&lt;br /&gt;
=== The types of settings ===&lt;br /&gt;
&lt;br /&gt;
There are several different types of configuration settings, divided up based on the possible inputs they take&lt;br /&gt;
&lt;br /&gt;
* Boolean: true, false, on, off&lt;br /&gt;
* Integer: Whole numbers  (2112)&lt;br /&gt;
* Float: Decimal values (21.12)&lt;br /&gt;
* Memory / Disk: Integers (2112) or &amp;quot;computer units&amp;quot; (512MB, 2112GB).  Avoid integers--you need to know the underlying unit to figure out what they mean.&lt;br /&gt;
* Time: &amp;quot;Time units&amp;quot; aka d,m,s (30s).  Sometimes the unit is left out; don&#039;t do that&lt;br /&gt;
* Strings: Single quoted text (&#039;pg_log&#039;)&lt;br /&gt;
* ENUMs: Strings, but from a specific list (&#039;WARNING&#039;, &#039;ERROR&#039;)&lt;br /&gt;
* Lists: A comma separated list of strings (&#039;&amp;quot;$user&amp;quot;,public,tsearch2) &lt;br /&gt;
&lt;br /&gt;
=== When they take effect ===&lt;br /&gt;
&lt;br /&gt;
PostgreSQL settings have different levels of flexibility for when they can be changed, usually related to internal code restrictions. The complete list of levels is:&lt;br /&gt;
&lt;br /&gt;
* Postmaster: requires restart of server &lt;br /&gt;
* Sighup: requires a HUP of the server, either by kill -HUP (usually -1), pg_ctl reload, or &amp;lt;tt&amp;gt;SELECT pg_reload_conf()&amp;lt;/tt&amp;gt;;&lt;br /&gt;
* User: can be set within individual sessions, take effect only within that session&lt;br /&gt;
* Internal: set at compile time, can&#039;t be changed, mainly for reference&lt;br /&gt;
* Backend: settings which must be set before session start&lt;br /&gt;
* Superuser: can be set at runtime for the server by superusers&lt;br /&gt;
&lt;br /&gt;
Most of the time you&#039;ll only use the first of these, but the second can be useful if you have a server you don&#039;t want to take down, while the user session settings can be helpful for some special situations.  You can tell which type of parameter a setting is by looking at the &amp;quot;context&amp;quot; field in the pg_settings view.&lt;br /&gt;
&lt;br /&gt;
=== Important notes about configuration files ===&lt;br /&gt;
&lt;br /&gt;
* Command line options override postgresql.auto.conf settings override postgresql.conf settings.&lt;br /&gt;
* If the same setting is listed multiple times, the last one wins.&lt;br /&gt;
* You can figure out the postgresql.conf location with &amp;lt;tt&amp;gt;SHOW config_file&amp;lt;/tt&amp;gt;.  It will generally be $PGDATA/postgresql.conf (&amp;lt;tt&amp;gt;SHOW data_directory&amp;lt;/tt&amp;gt;), but watch out for symbolic links, [http://www.postgresql.org/docs/current/static/app-pg-ctl.html#AEN93617 postmaster.opts] and other trickiness&lt;br /&gt;
* Lines with # are comments and have no effect. For a new database, this will mean the setting is using the default, but on running systems this may not hold true! Changes to the configuration files do not take effect without a reload/restart, so it&#039;s possible for the system to be running something different from what is in the file. &lt;br /&gt;
&lt;br /&gt;
=== Viewing the current settings === &lt;br /&gt;
&lt;br /&gt;
* Look at the configuration files.  This is generally not definitive!&lt;br /&gt;
* &amp;lt;tt&amp;gt;SHOW ALL&amp;lt;/tt&amp;gt;, &amp;lt;tt&amp;gt;SHOW &amp;lt;setting&amp;gt;&amp;lt;/tt&amp;gt; will show you the current value of the setting.  Watch out for session specific changes&lt;br /&gt;
* &amp;lt;tt&amp;gt;SELECT * FROM pg_settings&amp;lt;/tt&amp;gt; will label session specific changes as locally modified&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-connection.html#GUC-LISTEN-ADDRESSES listen_addresses]  ==&lt;br /&gt;
&lt;br /&gt;
By default, PostgreSQL only responds to connections from the local host.  If you want your server to be accessible from other systems via standard TCP/IP networking, you need to change listen_addresses from its default.  The usual approach is to set it to listen to all addresses like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;pre&amp;gt;&lt;br /&gt;
listen_addresses = &#039;*&#039;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And then control who can and cannot connect via the [http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html pg_hba.conf] file.&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-connection.html#GUC-MAX-CONNECTIONS max_connections]==&lt;br /&gt;
&lt;br /&gt;
max_connections sets exactly that:  the maximum number of client connections allowed.  This is very important to some of the below parameters (particularly work_mem) because there are some memory resources that are or can be allocated on a per-client basis, so the maximum number of clients suggests the maximum possible memory use.  Generally, PostgreSQL on good hardware can support a few hundred connections.  If you want to have thousands instead, you should consider using [[Replication, Clustering, and Connection Pooling|connection pooling software]] to reduce the connection overhead.&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-resource.html#GUC-SHARED-BUFFERS shared_buffers]==&lt;br /&gt;
&lt;br /&gt;
The shared_buffers configuration parameter determines how much memory is dedicated to PostgreSQL to use for caching data.  One reason the defaults are low is because on some platforms (like older Solaris versions and SGI), having large values requires invasive action like recompiling the kernel.  Even on a modern Linux system, the stock kernel will likely not allow setting shared_buffers to over 32MB without adjusting kernel settings first.  (PostgreSQL 9.3 and later use a different shared memory mechanism, so kernel settings will usually not have to be adjusted there.)&lt;br /&gt;
&lt;br /&gt;
If you have a system with 1GB or more of RAM, a reasonable starting value for shared_buffers is 1/4 of the memory in your system.  If you have less RAM you&#039;ll have to account more carefully for how much RAM the OS is taking up; closer to 15% is more typical there.  There are some workloads where even larger settings for shared_buffers are effective, but given the way PostgreSQL also relies on the operating system cache, it&#039;s unlikely you&#039;ll find using more than 40% of RAM to work better than a smaller amount.&lt;br /&gt;
&lt;br /&gt;
Be aware that if your system or PostgreSQL build is 32-bit, it might not be practical to set shared_buffers above 2 ~ 2.5GB. See [http://rhaas.blogspot.jp/2011/05/sharedbuffers-on-32-bit-systems.html this blog post] for details.&lt;br /&gt;
&lt;br /&gt;
Note that on Windows, large values for shared_buffers aren&#039;t as effective, and you may find better results keeping it relatively low and using the OS cache more instead.  On Windows the useful range is 64MB to 512MB.&lt;br /&gt;
&lt;br /&gt;
If you are running PostgreSQL 9.2 or earlier, it&#039;s likely you will have to increase the amount of memory your operating system allows you to allocate at once to set the value for shared_buffers this high.  On UNIX-like systems, if you set it above what&#039;s supported, you&#039;ll get a message like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&amp;lt;pre&amp;gt;&lt;br /&gt;
IpcMemoryCreate: shmget(key=5432001, size=415776768, 03600) failed: Invalid argument &lt;br /&gt;
&lt;br /&gt;
This error usually means that PostgreSQL&#039;s request for a shared memory &lt;br /&gt;
segment exceeded your kernel&#039;s SHMMAX parameter. You can either &lt;br /&gt;
reduce the request size or reconfigure the kernel with larger SHMMAX. &lt;br /&gt;
To reduce the request size (currently 415776768 bytes), reduce &lt;br /&gt;
PostgreSQL&#039;s shared_buffers parameter (currently 50000) and/or &lt;br /&gt;
its max_connections parameter (currently 12).&lt;br /&gt;
&amp;lt;/pre&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
See [http://www.postgresql.org/docs/current/static/kernel-resources.html Managing Kernel Resources] for details on how to correct this.&lt;br /&gt;
&lt;br /&gt;
Changing this setting requires restarting the database. Also, this is a hard allocation of memory; the whole thing gets allocated out of virtual memory when the database starts.&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-query.html#GUC-EFFECTIVE-CACHE-SIZE effective_cache_size]==&lt;br /&gt;
&lt;br /&gt;
effective_cache_size should be set to an estimate of how much memory is available for disk caching by the operating system and within the database itself, after taking into account what&#039;s used by the OS itself and other applications.  This is a guideline for how much memory you expect to be available in the OS and PostgreSQL buffer caches, not an allocation!  This value is used only by the PostgreSQL query planner to figure out whether plans it&#039;s considering would be expected to fit in RAM or not.  If it&#039;s set too low, indexes may not be used for executing queries the way you&#039;d expect.  The setting for shared_buffers is not taken into account here--only the effective_cache_size value is, so it should include memory dedicated to the database too.&lt;br /&gt;
&lt;br /&gt;
Setting effective_cache_size to 1/2 of total memory would be a normal conservative setting, and 3/4 of memory is a more aggressive but still reasonable amount.  You might find a better estimate by looking at your operating system&#039;s statistics. On UNIX-like systems, add the free+cached numbers from free or top to get an estimate. On Windows see the &amp;quot;System Cache&amp;quot; size in the Windows Task Manager&#039;s Performance tab.  Changing this setting does not require restarting the database (HUP is enough).&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-wal.html#RUNTIME-CONFIG-WAL-CHECKPOINTS checkpoint_segments checkpoint_completion_target]==&lt;br /&gt;
&lt;br /&gt;
PostgreSQL writes new transactions to the database in files called WAL segments that are 16MB in size.  Every time checkpoint_segments worth of these files have been written, by default 3, a checkpoint occurs.  Checkpoints can be resource intensive, and on a modern system doing one every 48MB will be a serious performance bottleneck.  Setting checkpoint_segments to a much larger value improves that.  Unless you&#039;re running on a very small configuration, you&#039;ll almost certainly be better setting this to at least 10, which also allows usefully increasing the completion target.&lt;br /&gt;
&lt;br /&gt;
For more write-heavy systems, values from 32 (checkpoint every 512MB) to 256 (every 4GB) are popular nowadays.  Very large settings use a lot more disk and will cause your database to take longer to recover, so make sure you&#039;re comfortable with both those things before large increases.  Normally the large settings (&amp;gt;64/1GB) are only used for bulk loading.  Note that whatever you choose for the segments, you&#039;ll still get a checkpoint at least every 5 minutes unless you also increase checkpoint_timeout (which isn&#039;t necessary on most systems).&lt;br /&gt;
&lt;br /&gt;
Checkpoint writes are spread out a bit while the system starts working toward the next checkpoint.  You can spread those writes out further, lowering the average write overhead, by increasing the checkpoint_completion_target parameter to its useful maximum of 0.9 (aim to finish by the time 90% of the next checkpoint is here) rather than the default of 0.5 (aim to finish when the next one is 50% done).  A setting of 0 gives something similar to the behavior of obsolete versions.  The main reason the default isn&#039;t just 0.9 is that you need a larger checkpoint_segments value than the default for broader spreading to work well.  For lots more information on checkpoint tuning, see [http://www.westnet.com/~gsmith/content/postgresql/chkp-bgw-83.htm Checkpoints and the Background Writer] (where you&#039;ll also learn why tuning the background writer parameters is challenging to do usefully).&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/routine-vacuuming.html#AUTOVACUUM autovacuum]==&lt;br /&gt;
&lt;br /&gt;
The autovacuum process takes care of several maintenance chores inside your database that you really need. Generally, if you think you need to turn regular vacuuming off because it&#039;s taking too much time or resources, that means you&#039;re doing it wrong.  The answer to almost all vacuuming problems is to vacuum more often, not less, so that each individual vacuum operation has less to clean up.&lt;br /&gt;
&lt;br /&gt;
However, it&#039;s acceptable to disable autovacuum for short periods of time, for instance when bulk loading large amounts of data.&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-logging.html logging]==&lt;br /&gt;
There are many things you can log that may or may not be important to you. You should investigate the documentation on all of the options, but here are some tips &amp;amp; tricks to get you started:&lt;br /&gt;
&lt;br /&gt;
*pgFouine is a tool used to analyze postgresql logs for performance tuning. If you plan to use this tool, it has specific logging requirements. Please check http://pgfouine.projects.postgresql.org/&lt;br /&gt;
&lt;br /&gt;
*pgFouine has been obsoleted by [http://dalibo.github.com/pgbadger PgBadger]&lt;br /&gt;
&lt;br /&gt;
*[https://github.com/darold/pgcluu PgCluu] is an handy tool from the author of PgBadger, and is a PostgreSQL performances monitoring and auditing tool.&lt;br /&gt;
&lt;br /&gt;
*log_destination &amp;amp; log_directory (&amp;amp; log_filename):  What you set these options to is not as important as knowing they can give you hints to determine where your database server is logging to. Best practice would be to try and make this as similar as possible across your servers.  Note that in some cases, the init script starting your database may be customizing the log destination in the command line used to start the database, overriding what&#039;s in the configuration files (and making it so you&#039;ll get different behavior if you run pg_ctl manually instead of using the init script).&lt;br /&gt;
&lt;br /&gt;
*log_min_error_statement:  You should probably make sure this is at least on error, so that you will see any SQL commands which cause an error. should be the default on recent versions. &lt;br /&gt;
&lt;br /&gt;
*log_min_duration_statement:  Not necessary for everyday use, but this can generate [[Logging Difficult Queries|logs of &amp;quot;slow queries&amp;quot;]] on your system. &lt;br /&gt;
&lt;br /&gt;
*log_line_prefix:  Appends information to the start of each line. A good generic recommendation is &#039;%t:%r:%u@%d:[%p]: &#039; : %t=timestamp, %u=db user name, %r=host connecting from, %d=database connecting to, %p=PID of connection. It may not be obvious what the PID is useful at first, but it can be vital for trying to troubleshoot problems in the future so better to put in the logs from the start.&lt;br /&gt;
&lt;br /&gt;
*log_statement:  Choices of none, ddl, mod, all. Using all in production leads to severe performance penalties. DDL can sometime be helpful to discover rogue changes made outside of your recommend processes, by &amp;quot;cowboy DBAs&amp;quot; for example.&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-query.html#GUC-DEFAULT-STATISTICS-TARGET default_statistics_target]==&lt;br /&gt;
&lt;br /&gt;
The database software collects statistics about each of the tables in your database to decide how to execute queries against it.  If you&#039;re not getting good execution query plans particularly on larger (or more varied) tables you should increase default_statistics_target then ANALYZE the database again (or wait for autovacuum to do it for you).  &lt;br /&gt;
&lt;br /&gt;
;PostgreSQL 8.4 and later&lt;br /&gt;
&lt;br /&gt;
The starting default_statistics_target value was raised from 10 to 100 in PostgreSQL 8.4.  Increases beyond 100 may still be useful, but this increase makes for greatly improved statistics estimation in the default configuration.  The maximum value for the parameter was also increased from 1000 to 10,000 in 8.4.&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-resource.html#GUC-WORK-MEM work_mem]==&lt;br /&gt;
&lt;br /&gt;
If you do a lot of complex sorts, and have a lot of memory, then increasing the &amp;lt;code&amp;gt;work_mem&amp;lt;/code&amp;gt; parameter allows PostgreSQL to do larger in-memory sorts which, unsurprisingly, will be faster than disk-based equivalents.&lt;br /&gt;
&lt;br /&gt;
This size is applied to each and every sort done by each user, and complex queries can use multiple working memory sort buffers. Set it to 50MB, and have 30 users submitting queries, and you are soon using 1.5GB of real memory. Furthermore, if a query involves doing merge sorts of 8 tables, that requires 8 times work_mem. You need to consider what you set max_connections to in order to size this parameter correctly. This is a setting where data warehouse systems, where users are submitting very large queries, can readily make use of many gigabytes of memory.&lt;br /&gt;
&lt;br /&gt;
[http://www.postgresql.org/docs/9.3/static/runtime-config-logging.html#GUC-LOG-TEMP-FILES log_temp_files] can be used to log sorts, hashes, and temp files which can be useful in figuring out if sorts are spilling to disk instead of fitting in memory. You can see sorts spilling to disk using &amp;lt;code&amp;gt;EXPLAIN ANALYZE&amp;lt;/code&amp;gt; plans as well. For example, if you see a line like &amp;lt;code&amp;gt;Sort Method:  external merge  Disk: 7526kB&amp;lt;/code&amp;gt; in the output of EXPLAIN ANALYZE, a &amp;lt;code&amp;gt;work_mem&amp;lt;/code&amp;gt; of at least 8MB would keep the intermediate data in memory and likely improve the query response time.&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-resource.html#GUC-MAINTENANCE-WORK-MEM maintenance_work_mem]==&lt;br /&gt;
&lt;br /&gt;
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&#039;t have many of them running concurrently, it&#039;s safe to set this value significantly larger than work_mem. Larger settings might improve performance for vacuuming and for restoring database dumps.&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-WAL-SYNC-METHOD wal_sync_method wal_buffers]==&lt;br /&gt;
&lt;br /&gt;
After every transaction, PostgreSQL forces a commit to disk out to its write-ahead log. This can be done a couple of ways, and on some platforms the other options are considerably faster than the conservative default.  open_sync is the most common non-default setting switched to, on platforms that support it but default to one of the fsync methods. See [http://www.westnet.com/~gsmith/content/postgresql/TuningPGWAL.htm Tuning PostgreSQL WAL Synchronization] for a lot of background on this topic. Note that open_sync writing is buggy on some platforms (such as [http://lwn.net/Articles/350219/ Linux]), and you should (as always) do plenty of tests under a heavy write load to make sure that you haven&#039;t made your system less stable with this change.  [[Reliable Writes]] contains more information on this topic.&lt;br /&gt;
&lt;br /&gt;
Linux kernels starting with version 2.6.33 will cause earlier versions of PostgreSQL to default to wal_sync_method=open_datasync; before that kernel release the default picked was always fdatasync.  This can cause a significant performance decrease when combined with small writes and/or small values for wal_buffers.&lt;br /&gt;
&lt;br /&gt;
Increasing wal_buffers from its tiny default of a small number of kilobytes is helpful for write-heavy systems.  Benchmarking generally suggests that just increasing to 1MB is enough for some large systems, and given the amount of RAM in modern servers allocating a full WAL segment (16MB, the useful upper-limit here) is reasonable. Changing wal_buffers requires a database restart.&lt;br /&gt;
&lt;br /&gt;
;PostgreSQL 9.1 and later&lt;br /&gt;
&lt;br /&gt;
Starting with PostgreSQL 9.1 wal_buffers defaults to being 1/32 of the size of shared_buffers, with an upper limit of 16MB (reached when shared_buffers=512MB).&lt;br /&gt;
&lt;br /&gt;
PostgreSQL 9.1 also changes the logic for selecting the default wal_sync_method such that on newer Linux kernels, it will still select fdatasync as its method--the same as on older Linux versions.&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-query.html#GUC-CONSTRAINT-EXCLUSION constraint_exclusion]==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;tt&amp;gt;constraint_exclusion&amp;lt;/tt&amp;gt; now defaults to a new choice: &amp;lt;tt&amp;gt;partition&amp;lt;/tt&amp;gt;. This will only enable constraint exclusion for partitioned tables which is the right thing to do in nearly all cases.&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-resource.html#GUC-MAX-PREPARED-TRANSACTIONS max_prepared_transactions]==&lt;br /&gt;
&lt;br /&gt;
This setting is used for managing 2 phase commit. If you do not use two phase commit (and if you don&#039;t know what it is, you don&#039;t use it), then you can set this value to 0. That will save a little bit of shared memory. For database systems with a large number (at least hundreds) of concurrent connections, be aware that this setting also affects the number of available lock-slots in pg_locks, so you may want to leave it at the default setting.  There is a formula for how much memory gets allocated [http://www.postgresql.org/docs/current/static/kernel-resources.html#SHARED-MEMORY-PARAMETERS in the docs] and in the default postgresql.conf.&lt;br /&gt;
&lt;br /&gt;
Changing max_prepared_transactions requires a server restart.&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT synchronous_commit]==&lt;br /&gt;
PostgreSQL can only safely use a write cache if it has a battery backup. See [http://www.postgresql.org/docs/current/static/wal-reliability.html WAL reliability] for an essential introduction to this topic.  No, really; go read that right now, it&#039;s vital to understand that if you want your database to work right.&lt;br /&gt;
&lt;br /&gt;
You may be limited to approximately 100 transaction commits per second per client in situations where you don&#039;t have such a durable write cache (and perhaps only 500/second even with lots of clients).&lt;br /&gt;
&lt;br /&gt;
For situations where a small amount of data loss is acceptable in return for a large boost in how many updates you can do to the database per second, consider switching synchronous commit off. This is particularly useful in the situation where you do not have a battery-backed write cache on your disk controller, because you could potentially get thousands of commits per second instead of just a few hundred.&lt;br /&gt;
&lt;br /&gt;
For obsolete versions of PostgreSQL, you may find people recommending that you set &#039;&#039;fsync=off&#039;&#039; to speed up writes on busy systems.  This is dangerous--a power loss could result in your database getting corrupted and not able to start again.  Synchronous commit doesn&#039;t introduce the risk of &#039;&#039;corruption&#039;&#039;, which is really bad, just some risk of data &#039;&#039;loss&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
==[http://www.postgresql.org/docs/current/static/runtime-config-query.html#GUC-RANDOM-PAGE-COST random_page_cost]==&lt;br /&gt;
This setting suggests to the optimizer how long it will take your disks to seek to a random disk page, as a multiple of how long a sequential read (with a cost of 1.0) takes. If you have particularly fast disks, as commonly found with  RAID arrays of SCSI disks, it may be appropriate to lower random_page_cost, which will encourage the query optimizer to use random access index scans. Some feel that 4.0 is always too large on current hardware; it&#039;s not unusual for administrators to standardize on always setting this between 2.0 and 3.0 instead.  In some cases that behavior is a holdover from earlier PostgreSQL versions where having random_page_cost too high was more likely to screw up plan optimization than it is now (and setting at or below 2.0 was regularly necessary). Since these cost estimates are just that--estimates--it shouldn&#039;t hurt to try lower values.&lt;br /&gt;
&lt;br /&gt;
But this not where you should start to search for plan problems. Note that random_page_cost is pretty far down this list (at the end in fact). If you are getting bad plans, this shouldn&#039;t be the first thing you look at, even though lowering this value may be effective. Instead, you should start by making sure autovacuum is working properly, that you are collecting enough statistics, and that you have correctly sized the memory parameters for your server--all the things gone over above.  After you&#039;ve done all those much more important things, if you&#039;re still getting bad plans &#039;&#039;then&#039;&#039; you should see if lowering random_page_cost is still useful.&lt;br /&gt;
&lt;br /&gt;
[[Category:Administration]] [[Category:Performance]]&lt;/div&gt;</summary>
		<author><name>Natmaka</name></author>
	</entry>
	<entry>
		<id>https://wiki.postgresql.org/index.php?title=User_talk:Accidentinjury&amp;diff=22175</id>
		<title>User talk:Accidentinjury</title>
		<link rel="alternate" type="text/html" href="https://wiki.postgresql.org/index.php?title=User_talk:Accidentinjury&amp;diff=22175"/>
		<updated>2014-04-22T06:45:03Z</updated>

		<summary type="html">&lt;p&gt;Natmaka: spam&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Natmaka</name></author>
	</entry>
	<entry>
		<id>https://wiki.postgresql.org/index.php?title=User:Accidentinjury&amp;diff=22173</id>
		<title>User:Accidentinjury</title>
		<link rel="alternate" type="text/html" href="https://wiki.postgresql.org/index.php?title=User:Accidentinjury&amp;diff=22173"/>
		<updated>2014-04-22T06:37:05Z</updated>

		<summary type="html">&lt;p&gt;Natmaka: spam&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Natmaka</name></author>
	</entry>
	<entry>
		<id>https://wiki.postgresql.org/index.php?title=Synchronous_replication&amp;diff=18770</id>
		<title>Synchronous replication</title>
		<link rel="alternate" type="text/html" href="https://wiki.postgresql.org/index.php?title=Synchronous_replication&amp;diff=18770"/>
		<updated>2012-12-30T17:51:02Z</updated>

		<summary type="html">&lt;p&gt;Natmaka: /* CODE */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Synchronous replication is available starting in PostgreSQL 9.1 by enabling the [http://developer.postgresql.org/pgdocs/postgres/runtime-config-wal.html#GUC-SYNCHRONOUS-STANDBY-NAMES synchronous_standby_names] parameter.  It includes user-controlled durability specified on the master using the [http://developer.postgresql.org/pgdocs/postgres/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT synchronous_commit] parameter.  The design also provides high throughput by allowing concurrent processes to handle the WAL stream. &lt;br /&gt;
&lt;br /&gt;
=WHAT&#039;S DIFFERENT ABOUT THIS PATCH?=&lt;br /&gt;
&lt;br /&gt;
The implementation in 9.1 includes several innovations, beyond [http://wiki.postgresql.org/wiki/Streaming_Replication Fujii Masao&#039;s work] providing an earlier synchronous replication implementation for PostgreSQL 9.0:&lt;br /&gt;
&lt;br /&gt;
* Low complexity of code on Standby&lt;br /&gt;
* User control: All decisions to wait take place on master, allowing fine-grained control of synchronous replication. Max replication level can also be set on the standby.&lt;br /&gt;
* Low bandwidth: Very small response packet size with no increase in number of responses when system is under high load means very little additional bandwidth required&lt;br /&gt;
* Performance: Standby processes work concurrently to give good overall throughput on standby and minimal latency in all modes. 4 performance options don&#039;t interfere with each other, so offer different levels of performance/durability alongside each other.&lt;br /&gt;
&lt;br /&gt;
These are major wins for PostgreSQL project over and above the basic sync rep feature.&lt;br /&gt;
&lt;br /&gt;
=SYNCHRONOUS REPLICATION OVERVIEW=&lt;br /&gt;
&lt;br /&gt;
Synchronous replication offers the guarantee that all changes made by a&lt;br /&gt;
transaction have been transferred to remote standby nodes. This is an&lt;br /&gt;
extension to the standard level of durability offered by a transaction&lt;br /&gt;
commit.&lt;br /&gt;
&lt;br /&gt;
When synchronous replication is requested the transaction will wait&lt;br /&gt;
after it commits until it receives confirmation that the transfer has&lt;br /&gt;
been successful. Waiting for confirmation increases the user&#039;s certainty&lt;br /&gt;
that the transfer has taken place but it also necessarily increases the&lt;br /&gt;
response time for the requesting transaction. Synchronous replication&lt;br /&gt;
usually requires carefully planned and placed standby servers to ensure&lt;br /&gt;
applications perform acceptably. Waiting doesn&#039;t utilise system&lt;br /&gt;
resources, but transaction locks continue to be held until the transfer&lt;br /&gt;
is confirmed. As a result, incautious use of synchronous replication&lt;br /&gt;
will lead to reduced performance for database applications.&lt;br /&gt;
&lt;br /&gt;
It may seem that there is a simple choice between durability and&lt;br /&gt;
performance. However, there is often a close relationship between the&lt;br /&gt;
importance of data and how busy the database needs to be, so this is&lt;br /&gt;
seldom a simple choice. With this patch, PostgreSQL now provides a range&lt;br /&gt;
of features designed to allow application architects to design a system&lt;br /&gt;
that has both good overall performance and yet good durability of the&lt;br /&gt;
most important data assets.&lt;br /&gt;
&lt;br /&gt;
PostgreSQL allows the application designer to specify the durability&lt;br /&gt;
level required via replication. This can be specified for the system&lt;br /&gt;
overall, though it can also be specified for individual transactions.&lt;br /&gt;
This allows to selectively provide highest levels of protection for&lt;br /&gt;
critical data. &lt;br /&gt;
&lt;br /&gt;
For example we, an application might consist of two types of work:&lt;br /&gt;
* 10% of changes are changes to important customer details&lt;br /&gt;
* 90% of changes are less important data that the business can more easily survive if it is lost, such as chat messages between users.&lt;br /&gt;
&lt;br /&gt;
With sync replication options specified at the application level (on the&lt;br /&gt;
master) we can offer sync rep for the most important changes, without&lt;br /&gt;
slowing down the bulk of the total workload. Application level options&lt;br /&gt;
are an important and practical tool for allowing the benefits of&lt;br /&gt;
synchronous replication for high performance applications.&lt;br /&gt;
&lt;br /&gt;
Without sync rep options specified at app level, we would have a choice&lt;br /&gt;
of either slowing down 90% of the workload because 10% of it is&lt;br /&gt;
important. Or giving up our durability goals because of performance. Or&lt;br /&gt;
splitting those two functions onto separate database servers so that we&lt;br /&gt;
can set options differently on each. None of those 3 options is truly&lt;br /&gt;
attractive.&lt;br /&gt;
&lt;br /&gt;
PostgreSQL also allows the system administrator the ability to specify&lt;br /&gt;
the service levels offered by standby servers. This allows multiple&lt;br /&gt;
standby servers to work together in various roles within a server farm.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Note:  the information about the parameters used here reflects and earlier version of this feature, and needs to be updated to reflect the form it was committed into 9.1 as&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Control of this feature relies on just 3 parameters:&lt;br /&gt;
On the master we can set&lt;br /&gt;
&lt;br /&gt;
* synchronous_replication&lt;br /&gt;
* synchronous_replication_timeout&lt;br /&gt;
&lt;br /&gt;
On the standby we can set&lt;br /&gt;
&lt;br /&gt;
* synchronous_replication_service&lt;br /&gt;
&lt;br /&gt;
These are explained in more detail in the following sections.&lt;br /&gt;
&lt;br /&gt;
=USER&#039;S OVERVIEW=&lt;br /&gt;
&lt;br /&gt;
Two new USERSET parameters on the master control this &lt;br /&gt;
* synchronous_replication = async (default) | recv | fsync | apply&lt;br /&gt;
* synchronous_replication_timeout = 0+ (0 means never timeout)&lt;br /&gt;
(default timeout 10sec)&lt;br /&gt;
&lt;br /&gt;
synchronous_replication = async is the default and means that no&lt;br /&gt;
synchronisaton is requested and so the commit will not wait. This is the&lt;br /&gt;
fastest setting. The word async is short for &amp;quot;asynchronous&amp;quot; and you may&lt;br /&gt;
see the term asynchronous replication discussed.&lt;br /&gt;
&lt;br /&gt;
Other settings refer to progressively higher levels of durability. The&lt;br /&gt;
higher the level of durability requested, the longer the wait for that&lt;br /&gt;
level of durability to be achieved.&lt;br /&gt;
&lt;br /&gt;
The precise meaning of the synchronous_replication settings is&lt;br /&gt;
* async  - commit does not wait for a standby before replying to user&lt;br /&gt;
* recv - commit waits until standby has received WAL&lt;br /&gt;
* fsync - commit waits until standby has received and fsynced WAL&lt;br /&gt;
* apply - commit waits until standby has received, fsynced and applied&lt;br /&gt;
This provides a simple, easily understood mechanism - and one that in&lt;br /&gt;
its default form is very similar to other RDBMS (e.g. Oracle).&lt;br /&gt;
&lt;br /&gt;
Note that in apply mode it is possible that the changes could be&lt;br /&gt;
accessible on the standby before the transaction that made the change&lt;br /&gt;
has been notified that the change is complete. Minor issue.&lt;br /&gt;
&lt;br /&gt;
Network delays may occur and the standby may also crash. If no reply is&lt;br /&gt;
received within the timeout we raise a NOTICE and then return successful&lt;br /&gt;
commit (no other action is possible). Note that it is possible to&lt;br /&gt;
request that we never timeout, so if no standby is available we wait for&lt;br /&gt;
it one to appear.&lt;br /&gt;
&lt;br /&gt;
When user commits, if the master does not have a currently connected&lt;br /&gt;
standby offering the required level of replication it will pick the next&lt;br /&gt;
best available level of replication. It is up to the sysadmin to provide&lt;br /&gt;
sufficient range of standby nodes to ensure at least one is available to&lt;br /&gt;
meet the requested service levels.&lt;br /&gt;
&lt;br /&gt;
If multiple standbys exist, the first standby to reply that the desired&lt;br /&gt;
level of durability has been achieved will release the waiting commit on&lt;br /&gt;
the master. Other options are available also via a plugin.&lt;br /&gt;
&lt;br /&gt;
==ADMINISTRATOR&#039;S OVERVIEW==&lt;br /&gt;
&lt;br /&gt;
On the standby we specify the highest type of replication service&lt;br /&gt;
offered by this standby server. This information is passed to the master&lt;br /&gt;
server when the standby connects for replication.&lt;br /&gt;
&lt;br /&gt;
This allows sysadmins to designate preferred standbys. It also allows&lt;br /&gt;
sysadmins to completely refuse to offer a synchronous replication&lt;br /&gt;
service, allowing a master to explicitly avoid synchronisation across&lt;br /&gt;
low bandwidth or high latency links.&lt;br /&gt;
&lt;br /&gt;
An additional parameter can be set in recovery.conf on the standby&lt;br /&gt;
&lt;br /&gt;
* synchronous_replication_service = async (def) | recv | fsync | apply&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= IMPLEMENTATION =&lt;br /&gt;
&lt;br /&gt;
Some aspects can be changed without significantly altering basic&lt;br /&gt;
proposal, for example master-specified standby registration wouldn&#039;t&lt;br /&gt;
really alter this very much.&lt;br /&gt;
&lt;br /&gt;
== STANDBY ==&lt;br /&gt;
&lt;br /&gt;
Master-controlled sync rep means that all user wait logic is centred on&lt;br /&gt;
the master. The details of sync rep requests on the master are not sent&lt;br /&gt;
to the standby, so there is no additional master to standby traffic nor&lt;br /&gt;
standby-side bookkeeping overheads. It also reduces complexity of&lt;br /&gt;
standby code.&lt;br /&gt;
&lt;br /&gt;
On the standby side the WAL Writer now operates during recovery. This&lt;br /&gt;
frees the WALReceiver to spend more time sending and receiving messages,&lt;br /&gt;
thereby minimising latency for users choosing the &amp;quot;recv&amp;quot; option. We now&lt;br /&gt;
have 3 processes handling WAL in an asynchronous pipeline: WAL Receiver&lt;br /&gt;
reads WAL data from the libpq connection then writes it to the WAL file,&lt;br /&gt;
the WAL Writer then fsyncs the WAL file and then the Startup process&lt;br /&gt;
replays the WAL. These processes act independently, so WAL pointers&lt;br /&gt;
(LSNs) are defined as WALReceiverLSN &amp;gt;= WALWriterLSN &amp;gt;= StartupLSN&lt;br /&gt;
&lt;br /&gt;
For each new message WALReceiver gets from master we issue a reply. Each&lt;br /&gt;
reply sends the current state of the 3 LSNs, so the reply message size&lt;br /&gt;
is only 28 bytes. Replies are sent half-duplex, i.e. we don&#039;t reply&lt;br /&gt;
while a new message is arriving.&lt;br /&gt;
&lt;br /&gt;
Note that there is absolutely not one reply per transaction on the&lt;br /&gt;
master. The standby knows nothing about what has been requested on the&lt;br /&gt;
master - replies always refer to the latest standby state and&lt;br /&gt;
effectively batch the responses.&lt;br /&gt;
&lt;br /&gt;
We act according to the requested synchronous_replication_service&lt;br /&gt;
* async -  no replies are sent&lt;br /&gt;
* recv -   replies are sent upon receipt only&lt;br /&gt;
* fsync -  replies are sent upon receipt and following fsync only&lt;br /&gt;
* apply -  replies are sent following receipt, fsync and apply.&lt;br /&gt;
&lt;br /&gt;
Replies are sent at the next available opportunity.&lt;br /&gt;
&lt;br /&gt;
In apply mode, when the WALReceiver is completely quiet this means we&lt;br /&gt;
send 3 reply messages - one at recv, one at fsync and one at apply. When&lt;br /&gt;
WALreceiver is busy the volume of messages does *not* increase since the&lt;br /&gt;
reply can&#039;t be sent until the current incoming message has been&lt;br /&gt;
received, after which we were going to reply anyway so it is not an&lt;br /&gt;
additional message. This means we piggyback an &amp;quot;apply&amp;quot; response onto a&lt;br /&gt;
later &amp;quot;recv&amp;quot; reply. As a result we get minimum response times in *all*&lt;br /&gt;
modes and maximum throughput is not impaired at all.&lt;br /&gt;
&lt;br /&gt;
When each new messages arrives from master the WALreceiver will write&lt;br /&gt;
the new data to the WAL file, wake the WALwriter and then reply. Each&lt;br /&gt;
new message from master receives a reply. If no further WAL data has&lt;br /&gt;
been received the WALreceiver waits on the latch. If the WALReceiver is&lt;br /&gt;
woken by WALWriter or Startup then it will reply to master with a&lt;br /&gt;
message, even if no new WAL has been received.&lt;br /&gt;
&lt;br /&gt;
So in both recv, fsync and apply cases a message as soon as possible to&lt;br /&gt;
master, so in all cases the wait time is minimised.&lt;br /&gt;
&lt;br /&gt;
When WALwriter is woken it sees if there is outstanding WAL data and if&lt;br /&gt;
so fsyncs it and wakes both WALreceiver and Startup. When no WAL remains&lt;br /&gt;
it waits on the latch.&lt;br /&gt;
&lt;br /&gt;
Startup process will wake WALreceiver when it has got to the end of the&lt;br /&gt;
latest chunk of WAL. If no further WAL is available then it waits on its&lt;br /&gt;
latch.&lt;br /&gt;
&lt;br /&gt;
== MASTER ==&lt;br /&gt;
&lt;br /&gt;
When user backends request sync rep they wait in a queue ordered by&lt;br /&gt;
requested LSN. A separate queue exists for each request mode.&lt;br /&gt;
&lt;br /&gt;
WALSender receives the 3 LSNs from the standby. It then wakes backends&lt;br /&gt;
in sequence from each queue.&lt;br /&gt;
&lt;br /&gt;
We provide a single wakeup rule: first WALSender to reply with the&lt;br /&gt;
requested XLogRecPtr will wake the backend. This guarantees that the WAL&lt;br /&gt;
data for the commit is transferred as requested to at least one standby.&lt;br /&gt;
That is sufficient for the use cases we have discussed.&lt;br /&gt;
&lt;br /&gt;
More complex wakeup rules would be possible via a plugin.&lt;br /&gt;
&lt;br /&gt;
Wait timeout would be set by individual backends with a timer, just as&lt;br /&gt;
we do for statement_timeout.&lt;br /&gt;
&lt;br /&gt;
= CODE =&lt;br /&gt;
&lt;br /&gt;
Total code to implement this is low. Breaks down into 5 areas&lt;br /&gt;
* Zoltan&#039;s libpq changes, included almost verbatim; fairly modular, so easy to replace with something we like better&lt;br /&gt;
* A new module syncrep.c and syncrep.h handle the backend wait/wakeup&lt;br /&gt;
* Light changes to allow streaming rep to make appropriate calls&lt;br /&gt;
* Small amount of code to allow WALWriter to be active in recovery&lt;br /&gt;
* Parameter code&lt;br /&gt;
No docs yet.&lt;br /&gt;
&lt;br /&gt;
The patch works on top of latches, though does not rely upon them for&lt;br /&gt;
its bulk performance characteristics. Latches only improve response time&lt;br /&gt;
for very low transaction rates; latches provide no additional throughput&lt;br /&gt;
for medium to high transaction rates.&lt;br /&gt;
&lt;br /&gt;
= PERFORMANCE ANALYSIS =&lt;br /&gt;
&lt;br /&gt;
Since we reply to each new chunk sent from master, &amp;quot;recv&amp;quot; mode has&lt;br /&gt;
absolutely minimal latency, especially since WALreceiver no longer&lt;br /&gt;
performs majority of fsyncs, as in 9.0 code. WALreceiver does not wait&lt;br /&gt;
for fsync or apply actions to complete before we reply, so fsync and&lt;br /&gt;
apply modes will always wait at least 2 standby-&amp;gt;master messages which&lt;br /&gt;
is appropriate because those actions will typically occur much later. &lt;br /&gt;
&lt;br /&gt;
This response mechanism offers highest responsive performance achievable&lt;br /&gt;
in &amp;quot;recv&amp;quot; mode and very good throughput under load. Note that the&lt;br /&gt;
different modes do not interfere with each other and can co-exist&lt;br /&gt;
happily while providing highest performance.&lt;br /&gt;
&lt;br /&gt;
Starting WALWriter is helpful, no matter what the&lt;br /&gt;
synchronous_replication_service specified.&lt;br /&gt;
&lt;br /&gt;
Can we optimise the sending of reply messages so that only chunks that&lt;br /&gt;
contain a commit deserve a reply? We could, but then we&#039;d need to do&lt;br /&gt;
extra work on the master to do bookkeeping of that. It would need to be&lt;br /&gt;
demonstrated that there is a performance issue big enough to be worth&lt;br /&gt;
the overhead on master and extra code.&lt;br /&gt;
&lt;br /&gt;
Is there an optimisation from reducing the number of options the standby&lt;br /&gt;
provides? The architecture on the standby side doesn&#039;t rely heavily on&lt;br /&gt;
the service level specified, nor does it rely in any way on the actual&lt;br /&gt;
sync rep mode specified on master. No further simplification is&lt;br /&gt;
possible.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= NOT YET IMPLEMENTED =&lt;br /&gt;
&lt;br /&gt;
* Timeout code &amp;amp; NOTICE&lt;br /&gt;
* Code and test plugin &lt;br /&gt;
* Loops in walsender, walwriter and receiver treat shutdown incorrectly&lt;br /&gt;
&lt;br /&gt;
I haven&#039;t yet looked at Fujii&#039;s code for this, not even sure where it&lt;br /&gt;
is, though hope to do so in the future. Zoltan&#039;s libpq code is the only&lt;br /&gt;
part of that patch used.&lt;br /&gt;
&lt;br /&gt;
So far I have spent 3.5 days on this and expect to complete tomorrow. I&lt;br /&gt;
think that throws out the argument that this proposal is too complex to&lt;br /&gt;
develop in this release. &lt;br /&gt;
&lt;br /&gt;
= OTHER ISSUES =&lt;br /&gt;
&lt;br /&gt;
* How should master behave when we shut it down?&lt;br /&gt;
* How should standby behave when we shut it down?&lt;br /&gt;
&lt;br /&gt;
[[Category:Replication]]&lt;/div&gt;</summary>
		<author><name>Natmaka</name></author>
	</entry>
	<entry>
		<id>https://wiki.postgresql.org/index.php?title=Synchronous_replication&amp;diff=18769</id>
		<title>Synchronous replication</title>
		<link rel="alternate" type="text/html" href="https://wiki.postgresql.org/index.php?title=Synchronous_replication&amp;diff=18769"/>
		<updated>2012-12-30T17:50:21Z</updated>

		<summary type="html">&lt;p&gt;Natmaka: /* SYNCHRONOUS REPLICATION OVERVIEW */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Synchronous replication is available starting in PostgreSQL 9.1 by enabling the [http://developer.postgresql.org/pgdocs/postgres/runtime-config-wal.html#GUC-SYNCHRONOUS-STANDBY-NAMES synchronous_standby_names] parameter.  It includes user-controlled durability specified on the master using the [http://developer.postgresql.org/pgdocs/postgres/runtime-config-wal.html#GUC-SYNCHRONOUS-COMMIT synchronous_commit] parameter.  The design also provides high throughput by allowing concurrent processes to handle the WAL stream. &lt;br /&gt;
&lt;br /&gt;
=WHAT&#039;S DIFFERENT ABOUT THIS PATCH?=&lt;br /&gt;
&lt;br /&gt;
The implementation in 9.1 includes several innovations, beyond [http://wiki.postgresql.org/wiki/Streaming_Replication Fujii Masao&#039;s work] providing an earlier synchronous replication implementation for PostgreSQL 9.0:&lt;br /&gt;
&lt;br /&gt;
* Low complexity of code on Standby&lt;br /&gt;
* User control: All decisions to wait take place on master, allowing fine-grained control of synchronous replication. Max replication level can also be set on the standby.&lt;br /&gt;
* Low bandwidth: Very small response packet size with no increase in number of responses when system is under high load means very little additional bandwidth required&lt;br /&gt;
* Performance: Standby processes work concurrently to give good overall throughput on standby and minimal latency in all modes. 4 performance options don&#039;t interfere with each other, so offer different levels of performance/durability alongside each other.&lt;br /&gt;
&lt;br /&gt;
These are major wins for PostgreSQL project over and above the basic sync rep feature.&lt;br /&gt;
&lt;br /&gt;
=SYNCHRONOUS REPLICATION OVERVIEW=&lt;br /&gt;
&lt;br /&gt;
Synchronous replication offers the guarantee that all changes made by a&lt;br /&gt;
transaction have been transferred to remote standby nodes. This is an&lt;br /&gt;
extension to the standard level of durability offered by a transaction&lt;br /&gt;
commit.&lt;br /&gt;
&lt;br /&gt;
When synchronous replication is requested the transaction will wait&lt;br /&gt;
after it commits until it receives confirmation that the transfer has&lt;br /&gt;
been successful. Waiting for confirmation increases the user&#039;s certainty&lt;br /&gt;
that the transfer has taken place but it also necessarily increases the&lt;br /&gt;
response time for the requesting transaction. Synchronous replication&lt;br /&gt;
usually requires carefully planned and placed standby servers to ensure&lt;br /&gt;
applications perform acceptably. Waiting doesn&#039;t utilise system&lt;br /&gt;
resources, but transaction locks continue to be held until the transfer&lt;br /&gt;
is confirmed. As a result, incautious use of synchronous replication&lt;br /&gt;
will lead to reduced performance for database applications.&lt;br /&gt;
&lt;br /&gt;
It may seem that there is a simple choice between durability and&lt;br /&gt;
performance. However, there is often a close relationship between the&lt;br /&gt;
importance of data and how busy the database needs to be, so this is&lt;br /&gt;
seldom a simple choice. With this patch, PostgreSQL now provides a range&lt;br /&gt;
of features designed to allow application architects to design a system&lt;br /&gt;
that has both good overall performance and yet good durability of the&lt;br /&gt;
most important data assets.&lt;br /&gt;
&lt;br /&gt;
PostgreSQL allows the application designer to specify the durability&lt;br /&gt;
level required via replication. This can be specified for the system&lt;br /&gt;
overall, though it can also be specified for individual transactions.&lt;br /&gt;
This allows to selectively provide highest levels of protection for&lt;br /&gt;
critical data. &lt;br /&gt;
&lt;br /&gt;
For example we, an application might consist of two types of work:&lt;br /&gt;
* 10% of changes are changes to important customer details&lt;br /&gt;
* 90% of changes are less important data that the business can more easily survive if it is lost, such as chat messages between users.&lt;br /&gt;
&lt;br /&gt;
With sync replication options specified at the application level (on the&lt;br /&gt;
master) we can offer sync rep for the most important changes, without&lt;br /&gt;
slowing down the bulk of the total workload. Application level options&lt;br /&gt;
are an important and practical tool for allowing the benefits of&lt;br /&gt;
synchronous replication for high performance applications.&lt;br /&gt;
&lt;br /&gt;
Without sync rep options specified at app level, we would have a choice&lt;br /&gt;
of either slowing down 90% of the workload because 10% of it is&lt;br /&gt;
important. Or giving up our durability goals because of performance. Or&lt;br /&gt;
splitting those two functions onto separate database servers so that we&lt;br /&gt;
can set options differently on each. None of those 3 options is truly&lt;br /&gt;
attractive.&lt;br /&gt;
&lt;br /&gt;
PostgreSQL also allows the system administrator the ability to specify&lt;br /&gt;
the service levels offered by standby servers. This allows multiple&lt;br /&gt;
standby servers to work together in various roles within a server farm.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Note:  the information about the parameters used here reflects and earlier version of this feature, and needs to be updated to reflect the form it was committed into 9.1 as&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Control of this feature relies on just 3 parameters:&lt;br /&gt;
On the master we can set&lt;br /&gt;
&lt;br /&gt;
* synchronous_replication&lt;br /&gt;
* synchronous_replication_timeout&lt;br /&gt;
&lt;br /&gt;
On the standby we can set&lt;br /&gt;
&lt;br /&gt;
* synchronous_replication_service&lt;br /&gt;
&lt;br /&gt;
These are explained in more detail in the following sections.&lt;br /&gt;
&lt;br /&gt;
=USER&#039;S OVERVIEW=&lt;br /&gt;
&lt;br /&gt;
Two new USERSET parameters on the master control this &lt;br /&gt;
* synchronous_replication = async (default) | recv | fsync | apply&lt;br /&gt;
* synchronous_replication_timeout = 0+ (0 means never timeout)&lt;br /&gt;
(default timeout 10sec)&lt;br /&gt;
&lt;br /&gt;
synchronous_replication = async is the default and means that no&lt;br /&gt;
synchronisaton is requested and so the commit will not wait. This is the&lt;br /&gt;
fastest setting. The word async is short for &amp;quot;asynchronous&amp;quot; and you may&lt;br /&gt;
see the term asynchronous replication discussed.&lt;br /&gt;
&lt;br /&gt;
Other settings refer to progressively higher levels of durability. The&lt;br /&gt;
higher the level of durability requested, the longer the wait for that&lt;br /&gt;
level of durability to be achieved.&lt;br /&gt;
&lt;br /&gt;
The precise meaning of the synchronous_replication settings is&lt;br /&gt;
* async  - commit does not wait for a standby before replying to user&lt;br /&gt;
* recv - commit waits until standby has received WAL&lt;br /&gt;
* fsync - commit waits until standby has received and fsynced WAL&lt;br /&gt;
* apply - commit waits until standby has received, fsynced and applied&lt;br /&gt;
This provides a simple, easily understood mechanism - and one that in&lt;br /&gt;
its default form is very similar to other RDBMS (e.g. Oracle).&lt;br /&gt;
&lt;br /&gt;
Note that in apply mode it is possible that the changes could be&lt;br /&gt;
accessible on the standby before the transaction that made the change&lt;br /&gt;
has been notified that the change is complete. Minor issue.&lt;br /&gt;
&lt;br /&gt;
Network delays may occur and the standby may also crash. If no reply is&lt;br /&gt;
received within the timeout we raise a NOTICE and then return successful&lt;br /&gt;
commit (no other action is possible). Note that it is possible to&lt;br /&gt;
request that we never timeout, so if no standby is available we wait for&lt;br /&gt;
it one to appear.&lt;br /&gt;
&lt;br /&gt;
When user commits, if the master does not have a currently connected&lt;br /&gt;
standby offering the required level of replication it will pick the next&lt;br /&gt;
best available level of replication. It is up to the sysadmin to provide&lt;br /&gt;
sufficient range of standby nodes to ensure at least one is available to&lt;br /&gt;
meet the requested service levels.&lt;br /&gt;
&lt;br /&gt;
If multiple standbys exist, the first standby to reply that the desired&lt;br /&gt;
level of durability has been achieved will release the waiting commit on&lt;br /&gt;
the master. Other options are available also via a plugin.&lt;br /&gt;
&lt;br /&gt;
==ADMINISTRATOR&#039;S OVERVIEW==&lt;br /&gt;
&lt;br /&gt;
On the standby we specify the highest type of replication service&lt;br /&gt;
offered by this standby server. This information is passed to the master&lt;br /&gt;
server when the standby connects for replication.&lt;br /&gt;
&lt;br /&gt;
This allows sysadmins to designate preferred standbys. It also allows&lt;br /&gt;
sysadmins to completely refuse to offer a synchronous replication&lt;br /&gt;
service, allowing a master to explicitly avoid synchronisation across&lt;br /&gt;
low bandwidth or high latency links.&lt;br /&gt;
&lt;br /&gt;
An additional parameter can be set in recovery.conf on the standby&lt;br /&gt;
&lt;br /&gt;
* synchronous_replication_service = async (def) | recv | fsync | apply&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= IMPLEMENTATION =&lt;br /&gt;
&lt;br /&gt;
Some aspects can be changed without significantly altering basic&lt;br /&gt;
proposal, for example master-specified standby registration wouldn&#039;t&lt;br /&gt;
really alter this very much.&lt;br /&gt;
&lt;br /&gt;
== STANDBY ==&lt;br /&gt;
&lt;br /&gt;
Master-controlled sync rep means that all user wait logic is centred on&lt;br /&gt;
the master. The details of sync rep requests on the master are not sent&lt;br /&gt;
to the standby, so there is no additional master to standby traffic nor&lt;br /&gt;
standby-side bookkeeping overheads. It also reduces complexity of&lt;br /&gt;
standby code.&lt;br /&gt;
&lt;br /&gt;
On the standby side the WAL Writer now operates during recovery. This&lt;br /&gt;
frees the WALReceiver to spend more time sending and receiving messages,&lt;br /&gt;
thereby minimising latency for users choosing the &amp;quot;recv&amp;quot; option. We now&lt;br /&gt;
have 3 processes handling WAL in an asynchronous pipeline: WAL Receiver&lt;br /&gt;
reads WAL data from the libpq connection then writes it to the WAL file,&lt;br /&gt;
the WAL Writer then fsyncs the WAL file and then the Startup process&lt;br /&gt;
replays the WAL. These processes act independently, so WAL pointers&lt;br /&gt;
(LSNs) are defined as WALReceiverLSN &amp;gt;= WALWriterLSN &amp;gt;= StartupLSN&lt;br /&gt;
&lt;br /&gt;
For each new message WALReceiver gets from master we issue a reply. Each&lt;br /&gt;
reply sends the current state of the 3 LSNs, so the reply message size&lt;br /&gt;
is only 28 bytes. Replies are sent half-duplex, i.e. we don&#039;t reply&lt;br /&gt;
while a new message is arriving.&lt;br /&gt;
&lt;br /&gt;
Note that there is absolutely not one reply per transaction on the&lt;br /&gt;
master. The standby knows nothing about what has been requested on the&lt;br /&gt;
master - replies always refer to the latest standby state and&lt;br /&gt;
effectively batch the responses.&lt;br /&gt;
&lt;br /&gt;
We act according to the requested synchronous_replication_service&lt;br /&gt;
* async -  no replies are sent&lt;br /&gt;
* recv -   replies are sent upon receipt only&lt;br /&gt;
* fsync -  replies are sent upon receipt and following fsync only&lt;br /&gt;
* apply -  replies are sent following receipt, fsync and apply.&lt;br /&gt;
&lt;br /&gt;
Replies are sent at the next available opportunity.&lt;br /&gt;
&lt;br /&gt;
In apply mode, when the WALReceiver is completely quiet this means we&lt;br /&gt;
send 3 reply messages - one at recv, one at fsync and one at apply. When&lt;br /&gt;
WALreceiver is busy the volume of messages does *not* increase since the&lt;br /&gt;
reply can&#039;t be sent until the current incoming message has been&lt;br /&gt;
received, after which we were going to reply anyway so it is not an&lt;br /&gt;
additional message. This means we piggyback an &amp;quot;apply&amp;quot; response onto a&lt;br /&gt;
later &amp;quot;recv&amp;quot; reply. As a result we get minimum response times in *all*&lt;br /&gt;
modes and maximum throughput is not impaired at all.&lt;br /&gt;
&lt;br /&gt;
When each new messages arrives from master the WALreceiver will write&lt;br /&gt;
the new data to the WAL file, wake the WALwriter and then reply. Each&lt;br /&gt;
new message from master receives a reply. If no further WAL data has&lt;br /&gt;
been received the WALreceiver waits on the latch. If the WALReceiver is&lt;br /&gt;
woken by WALWriter or Startup then it will reply to master with a&lt;br /&gt;
message, even if no new WAL has been received.&lt;br /&gt;
&lt;br /&gt;
So in both recv, fsync and apply cases a message as soon as possible to&lt;br /&gt;
master, so in all cases the wait time is minimised.&lt;br /&gt;
&lt;br /&gt;
When WALwriter is woken it sees if there is outstanding WAL data and if&lt;br /&gt;
so fsyncs it and wakes both WALreceiver and Startup. When no WAL remains&lt;br /&gt;
it waits on the latch.&lt;br /&gt;
&lt;br /&gt;
Startup process will wake WALreceiver when it has got to the end of the&lt;br /&gt;
latest chunk of WAL. If no further WAL is available then it waits on its&lt;br /&gt;
latch.&lt;br /&gt;
&lt;br /&gt;
== MASTER ==&lt;br /&gt;
&lt;br /&gt;
When user backends request sync rep they wait in a queue ordered by&lt;br /&gt;
requested LSN. A separate queue exists for each request mode.&lt;br /&gt;
&lt;br /&gt;
WALSender receives the 3 LSNs from the standby. It then wakes backends&lt;br /&gt;
in sequence from each queue.&lt;br /&gt;
&lt;br /&gt;
We provide a single wakeup rule: first WALSender to reply with the&lt;br /&gt;
requested XLogRecPtr will wake the backend. This guarantees that the WAL&lt;br /&gt;
data for the commit is transferred as requested to at least one standby.&lt;br /&gt;
That is sufficient for the use cases we have discussed.&lt;br /&gt;
&lt;br /&gt;
More complex wakeup rules would be possible via a plugin.&lt;br /&gt;
&lt;br /&gt;
Wait timeout would be set by individual backends with a timer, just as&lt;br /&gt;
we do for statement_timeout.&lt;br /&gt;
&lt;br /&gt;
= CODE =&lt;br /&gt;
&lt;br /&gt;
Total code to implement this is low. Breaks down into 5 areas&lt;br /&gt;
* Zoltan&#039;s libpq changes, included almost verbatim; fairly modular, so&lt;br /&gt;
easy to replace with something we like better&lt;br /&gt;
* A new module syncrep.c and syncrep.h handle the backend wait/wakeup&lt;br /&gt;
* Light changes to allow streaming rep to make appropriate calls&lt;br /&gt;
* Small amount of code to allow WALWriter to be active in recovery&lt;br /&gt;
* Parameter code&lt;br /&gt;
No docs yet.&lt;br /&gt;
&lt;br /&gt;
The patch works on top of latches, though does not rely upon them for&lt;br /&gt;
its bulk performance characteristics. Latches only improve response time&lt;br /&gt;
for very low transaction rates; latches provide no additional throughput&lt;br /&gt;
for medium to high transaction rates.&lt;br /&gt;
&lt;br /&gt;
= PERFORMANCE ANALYSIS =&lt;br /&gt;
&lt;br /&gt;
Since we reply to each new chunk sent from master, &amp;quot;recv&amp;quot; mode has&lt;br /&gt;
absolutely minimal latency, especially since WALreceiver no longer&lt;br /&gt;
performs majority of fsyncs, as in 9.0 code. WALreceiver does not wait&lt;br /&gt;
for fsync or apply actions to complete before we reply, so fsync and&lt;br /&gt;
apply modes will always wait at least 2 standby-&amp;gt;master messages which&lt;br /&gt;
is appropriate because those actions will typically occur much later. &lt;br /&gt;
&lt;br /&gt;
This response mechanism offers highest responsive performance achievable&lt;br /&gt;
in &amp;quot;recv&amp;quot; mode and very good throughput under load. Note that the&lt;br /&gt;
different modes do not interfere with each other and can co-exist&lt;br /&gt;
happily while providing highest performance.&lt;br /&gt;
&lt;br /&gt;
Starting WALWriter is helpful, no matter what the&lt;br /&gt;
synchronous_replication_service specified.&lt;br /&gt;
&lt;br /&gt;
Can we optimise the sending of reply messages so that only chunks that&lt;br /&gt;
contain a commit deserve a reply? We could, but then we&#039;d need to do&lt;br /&gt;
extra work on the master to do bookkeeping of that. It would need to be&lt;br /&gt;
demonstrated that there is a performance issue big enough to be worth&lt;br /&gt;
the overhead on master and extra code.&lt;br /&gt;
&lt;br /&gt;
Is there an optimisation from reducing the number of options the standby&lt;br /&gt;
provides? The architecture on the standby side doesn&#039;t rely heavily on&lt;br /&gt;
the service level specified, nor does it rely in any way on the actual&lt;br /&gt;
sync rep mode specified on master. No further simplification is&lt;br /&gt;
possible.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= NOT YET IMPLEMENTED =&lt;br /&gt;
&lt;br /&gt;
* Timeout code &amp;amp; NOTICE&lt;br /&gt;
* Code and test plugin &lt;br /&gt;
* Loops in walsender, walwriter and receiver treat shutdown incorrectly&lt;br /&gt;
&lt;br /&gt;
I haven&#039;t yet looked at Fujii&#039;s code for this, not even sure where it&lt;br /&gt;
is, though hope to do so in the future. Zoltan&#039;s libpq code is the only&lt;br /&gt;
part of that patch used.&lt;br /&gt;
&lt;br /&gt;
So far I have spent 3.5 days on this and expect to complete tomorrow. I&lt;br /&gt;
think that throws out the argument that this proposal is too complex to&lt;br /&gt;
develop in this release. &lt;br /&gt;
&lt;br /&gt;
= OTHER ISSUES =&lt;br /&gt;
&lt;br /&gt;
* How should master behave when we shut it down?&lt;br /&gt;
* How should standby behave when we shut it down?&lt;br /&gt;
&lt;br /&gt;
[[Category:Replication]]&lt;/div&gt;</summary>
		<author><name>Natmaka</name></author>
	</entry>
	<entry>
		<id>https://wiki.postgresql.org/index.php?title=Priorities&amp;diff=18664</id>
		<title>Priorities</title>
		<link rel="alternate" type="text/html" href="https://wiki.postgresql.org/index.php?title=Priorities&amp;diff=18664"/>
		<updated>2012-12-02T17:17:14Z</updated>

		<summary type="html">&lt;p&gt;Natmaka: /* Is CPU really the bottleneck? */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Prioritizing users, queries, or databases ==&lt;br /&gt;
&lt;br /&gt;
PostgreSQL has no facilities to limit what resources a particular user, query, or database consumes, or correspondingly to set priorities such that one user/query/database gets more resources than others.  It&#039;s necessary to use operating system facilities to achieve what limited prioritization is possible.&lt;br /&gt;
&lt;br /&gt;
There are three main resources that PostgreSQL users, queries, and databases will contend for:&lt;br /&gt;
&lt;br /&gt;
* Memory&lt;br /&gt;
* CPU&lt;br /&gt;
* Disk I/O&lt;br /&gt;
&lt;br /&gt;
Of these, disk I/O is commonly a bottleneck for database applications, but that&#039;s not always the case. Some schema designs and queries are particularly CPU heavy.  Others really benefit from having lots of memory to work with, typically for sorting.&lt;br /&gt;
&lt;br /&gt;
== Are priorities really the problem? ==&lt;br /&gt;
&lt;br /&gt;
Before struggling too much with prioritizing your queries/users/databases, it&#039;s worthwhile to optimize your queries and [[Tuning_Your_PostgreSQL_Server|tune your database]]. You may find that you can get perfectly acceptable performance without playing with priorities or taking extreme measures, using techniques such as:&lt;br /&gt;
&lt;br /&gt;
* [[Using_EXPLAIN|Improving your queries]]&lt;br /&gt;
* Tune autovacuum to reduce bloat&lt;br /&gt;
* [[Performance_Optimization|Generally polishing your cluster&#039;s performance]]&lt;br /&gt;
* Avoiding use of [[VACUUM FULL]].  That can lead to bloated indexes that eat lots of memory and take forever to scan, wasting disk I/O bandwidth. See the wiki page on [[VACUUM FULL]] for more information.&lt;br /&gt;
&lt;br /&gt;
=== Is CPU really the bottleneck? ===&lt;br /&gt;
&lt;br /&gt;
People often complain of pegged (100%) CPU and assume that&#039;s the cause of database slowdowns. That&#039;s not necessarily the case - a system may show an apparent 100% CPU use, but in fact be mainly limited by I/O bandwidth. Consider the following test, which starts 20 `dd&#039; processes, each reading a different 1GB block from the hard disk (here: /dev/md0) at 1GB offsets (run the test as root).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  sync ; sh -c &amp;quot;echo 3 &amp;gt; /proc/sys/vm/drop_caches&lt;br /&gt;
  for i in `seq 1 20`; do &lt;br /&gt;
  ( dd if=/dev/md0 bs=1M count=1000 skip=$(($i * 1000)) of=/dev/null &amp;amp;)&lt;br /&gt;
  done&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
results in `top&#039; output of:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;                          &lt;br /&gt;
top - 14:51:55 up 3 days,  2:09,  5 users,  load average: 10.92, 4.94, 2.93&lt;br /&gt;
Tasks: 259 total,   3 running, 256 sleeping,   0 stopped,   0 zombie&lt;br /&gt;
Cpu(s):  1.6%us, 15.0%sy,  0.0%ni,  0.0%id, 78.6%wa,  0.8%hi,  4.0%si,  0.0%st&lt;br /&gt;
Mem:   4055728k total,  3843408k used,   212320k free,   749448k buffers&lt;br /&gt;
Swap:  2120544k total,     4144k used,  2116400k free,  2303356k cached&lt;br /&gt;
&lt;br /&gt;
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                            &lt;br /&gt;
   33 root      15  -5     0    0    0 R    5  0.0   0:26.67 kswapd0                            &lt;br /&gt;
  904 root      20   0  4152 1772  628 D    5  0.0   0:00.62 dd                                 &lt;br /&gt;
  874 root      20   0  4152 1768  628 D    3  0.0   0:00.74 dd                                 &lt;br /&gt;
  908 root      20   0  4152 1768  628 D    3  0.0   0:00.80 dd                                 &lt;br /&gt;
  888 root      20   0  4152 1772  628 D    3  0.0   0:00.44 dd                                 &lt;br /&gt;
  906 root      20   0  4152 1772  628 D    3  0.0   0:00.56 dd                                 &lt;br /&gt;
  894 root      20   0  4152 1768  628 D    2  0.0   0:00.49 dd                                 &lt;br /&gt;
  902 root      20   0  4152 1772  628 D    2  0.0   0:00.46 dd   &lt;br /&gt;
  .... etc ....                              &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
... which could be confused for a busy CPU, but is really load caused by disk I/O.  The key warning sign here is the presence of a high iowait cpu percentage (&amp;quot;%wa&amp;quot;), indicating that much of the apparent load is actually caused by delays in the I/O subsystem.  Most of the `dd&#039; processes are in &#039;D&#039; state - ie uninterruptable sleep in a system call - and if you check &amp;quot;wchan&amp;quot; with &amp;quot;ps&amp;quot; you&#039;ll see that they&#039;re sleeping waiting for I/O. &lt;br /&gt;
&lt;br /&gt;
Rather than assuming that CPU contention is the issue, it&#039;s a good idea to use the available [[Performance Analysis Tools]] to get a better idea of where your system bottlenecks really are.&lt;br /&gt;
&lt;br /&gt;
== Prioritizing CPU ==&lt;br /&gt;
&lt;br /&gt;
For adjusting the CPU priority of PostgreSQL processes, you can use &amp;quot;renice&amp;quot; (on UNIX systems), but it&#039;s a bit clumsy to do since you need to &amp;quot;renice&amp;quot; the backend of interest, not the client program connected to that backend. You can get the backend process id using the SQL query &amp;quot;SELECT pg_backend_pid()&amp;quot; or by looking at the pg_stat_activity view.&lt;br /&gt;
&lt;br /&gt;
One significant limitation of &amp;quot;renice&amp;quot;, or any approach based on the setpriority() call, is that on most UNIX-like platforms one must be root to lower the numerical priority value (i.e. schedule the process to run more urgently) of a process.&lt;br /&gt;
&lt;br /&gt;
Increasing the priority of important backends, via a root user&#039;s call to &amp;quot;renice&amp;quot;, instead of lowering the priority of unimportant ones, may be more effective.&lt;br /&gt;
&lt;br /&gt;
== prioritize module ==&lt;br /&gt;
The [http://pgxn.org/dist/prioritize/ prioritize] extension lets users adjust the CPU priority, in the same way that &amp;quot;renice&amp;quot; does, via the SQL function set_backend_priority(). Normal users may increase the priority value of any backend process running under the same username. Superusers may increase the priority value of any backend process. Just like with using &amp;quot;renice&amp;quot; manually, it is not possible to lower a backend&#039;s priority value, since PostgreSQL will not be running as the &amp;quot;root&amp;quot; user.&lt;br /&gt;
&lt;br /&gt;
If you know your application will be running an unimportant CPU-heavy query, you could have it call set_backend_priority(pg_backend_pid(), 20) after installing the &amp;quot;prioritize&amp;quot; module, so that the process is scheduled for the lowest possible urgency.&lt;br /&gt;
&lt;br /&gt;
== Prioritizing I/O ==&lt;br /&gt;
&lt;br /&gt;
I/O is harder. Some operating systems offer I/O priorities for&lt;br /&gt;
processes, like Linux&#039;s ionice, and you&#039;d think you could use these in a&lt;br /&gt;
similar way to how you use &#039;nice&#039;. Unfortunately, that won&#039;t work particularly well,&lt;br /&gt;
because a lot of the work PostgreSQL does - especially disk writes - are&lt;br /&gt;
done via a separate background writer process working from memory shared&lt;br /&gt;
by all backends. Similarly, the write-ahead logs are managed by their&lt;br /&gt;
own process via shared memory. Because of those two, it&#039;s very hard to effectively give one&lt;br /&gt;
user priority over another for writes. ionice should be moderately&lt;br /&gt;
effective for reads, though.&lt;br /&gt;
&lt;br /&gt;
As with &amp;quot;nice&amp;quot;, effective control on a per-connection level will require the addition of appropriate helper&lt;br /&gt;
functions, and user co-operation is required to achieve per-user priorities.&lt;br /&gt;
&lt;br /&gt;
Better separation of I/O workloads will require [[Prioritizing_databases_by_separating_into_multiple_clusters|cluster separation]], which has its own costs and is only effective on the per-database level.&lt;br /&gt;
&lt;br /&gt;
== Prioritizing memory ==&lt;br /&gt;
&lt;br /&gt;
PostgreSQL does have some [[Tuning_Your_PostgreSQL_Server|tunable parameters]] for memory use that are per-client, particularly &amp;lt;code&amp;gt;[http://www.postgresql.org/docs/current/static/runtime-config-resource.html#GUC-WORK-MEM work_mem]&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;[http://www.postgresql.org/docs/current/static/runtime-config-resource.html#GUC-MAINTENANCE-WORK-MEM maintenance_work_mem]&amp;lt;/code&amp;gt;.  These may be set within a given connection to allow that backend to use more than the usual amount of memory for things like sorts and index creation. You can set these to conservative, low values in &amp;lt;code&amp;gt;postgresql.conf&amp;lt;/code&amp;gt; then use the &amp;lt;code&amp;gt;SET&amp;lt;/code&amp;gt; command to assign higher values to them for a particular backend, eg &amp;lt;code&amp;gt;SET work_mem = &#039;100MB&#039;;&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
You can set different values for &amp;lt;code&amp;gt;work_mem&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;maintenance_work_mem&amp;lt;/code&amp;gt; using per-user GUC variables. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
ALTER USER myuser SET work_mem = &#039;50MB&#039;;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You cannot affect the shared memory allocation done with settings like shared_buffers this way, that value is fixed at database startup time and can&#039;t be changed without restarting it.&lt;br /&gt;
&lt;br /&gt;
There&#039;s no easy way in most operating systems to prioritize memory allocations, so that for example the OS would prefer to swap one backend&#039;s memory out instead of another&#039;s.&lt;br /&gt;
&lt;br /&gt;
== External links ==&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.cmu.edu/~harchol/Papers/actual-icde-submission.pdf CMU article studying CPU priorities on Postgres and DB2 on TPC-C and TPC-W workloads]&lt;br /&gt;
&lt;br /&gt;
== Credits ==&lt;br /&gt;
Page initially by [[User:Ringerc|Ringerc]] 02:34, 26 November 2009 (UTC)&lt;br /&gt;
&lt;br /&gt;
[[Category:FAQ]] [[Category:Performance]]&lt;/div&gt;</summary>
		<author><name>Natmaka</name></author>
	</entry>
	<entry>
		<id>https://wiki.postgresql.org/index.php?title=Performance_Optimization&amp;diff=17797</id>
		<title>Performance Optimization</title>
		<link rel="alternate" type="text/html" href="https://wiki.postgresql.org/index.php?title=Performance_Optimization&amp;diff=17797"/>
		<updated>2012-06-12T16:02:49Z</updated>

		<summary type="html">&lt;p&gt;Natmaka: /* General Setup and Optimization */ link update&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== General Setup and Optimization ==&lt;br /&gt;
* [[Tuning Your PostgreSQL Server]] by Greg Smith, Robert Treat, and Christopher Browne&lt;br /&gt;
* [http://www.revsys.com/writings/postgresql-performance.html Performance Tuning PostgreSQL] by Frank Wiles&lt;br /&gt;
* [http://www.pgcon.org/2008/schedule/events/104.en.html GUCs: A Three Hour Tour] by Josh Berkus.  Also useful here is his [http://pgfoundry.org/docman/view.php/1000106/84/calcfactors.sxc tuning OpenOffice spreadsheet], which suggests tuning values for 5 different types of workloads. &lt;br /&gt;
* [http://linuxfinances.info/info/quickstart.html QuickStart Guide to Tuning  PostgreSQL] by Christopher Browne&lt;br /&gt;
* [http://www.westnet.com/~gsmith/content/postgresql/pg-5minute.htm 5-Minute Introduction to PostgreSQL Performance] by Greg Smith&lt;br /&gt;
* [http://www.varlena.com/GeneralBits/Tidbits/annotated_conf_e.html Annotated postgresql.conf] by Josh Berkus and Shridhar Daithankar (older V7.4 targeted version of material covered in the GUC tour referenced above)&lt;br /&gt;
* [http://www.varlena.com/GeneralBits/Tidbits/perf.html Performance Tuning] by Josh Berkus and Shridhar Daithankar&lt;br /&gt;
* [http://www.zope.org/Members/pupq/pg_in_aggregates Replacing Slow Loops in PostgreSQL] by Joel Burton&lt;br /&gt;
* [http://www.postgresql.org/files/documentation/books/aw_pgsql/hw_performance/ PostgreSQL Hardware Performance Tuning] by Bruce Momjian&lt;br /&gt;
* [http://www.targeted.org/articles/databases/fragmentation.html The effects of data fragmentation in a mixed load database] by Dmitry Dvoinikov&lt;br /&gt;
* [http://www.2ndquadrant.com/static/2quad/media/pdfs/talks/Postgres_Performance_Update83.pdf PostgreSQL Performance Features in 8.3] by Simon Riggs&lt;br /&gt;
* [http://www.2ndquadrant.com/static/2quad/media/pdfs/talks/Postgres_Performance_Update84.pdf PostgreSQL Performance Features in 8.4] by Simon Riggs&lt;br /&gt;
&lt;br /&gt;
Performance courses are available from a number of companies. Check [http://www.postgresql.org/about/eventarchive events and trainings] for further details.&lt;br /&gt;
&lt;br /&gt;
==Critical maintenance for performance==&lt;br /&gt;
*[[Introduction to VACUUM, ANALYZE, EXPLAIN, and COUNT]] by Jim Nasby.&lt;br /&gt;
*[[VACUUM FULL]] and why you should avoid it&lt;br /&gt;
*[[Planner Statistics]]&lt;br /&gt;
*[[Using EXPLAIN]]&lt;br /&gt;
*[[Logging Difficult Queries]]&lt;br /&gt;
*[[Logging Checkpoints]]&lt;br /&gt;
*[http://www.westnet.com/~gsmith/content/postgresql/chkp-bgw-83.htm Checkpoints and the Background Writer:  PostgreSQL 8.3 Improvements and Migration] by Greg Smith&lt;br /&gt;
*[[Bulk Loading and Restores]]&lt;br /&gt;
*[[Performance Analysis Tools]] by Craig Ringer&lt;br /&gt;
&lt;br /&gt;
== Database architecture ==&lt;br /&gt;
* [[Priorities|Limiting and prioritizing user/query/database resource usage]] by Craig Ringer&lt;br /&gt;
* [[Prioritizing databases by separating into multiple clusters]] by Craig Ringer&lt;br /&gt;
* [[Clustering]]&lt;br /&gt;
* [[Shared Storage]]&lt;br /&gt;
&lt;br /&gt;
==Database Hardware Selection and Setup==&lt;br /&gt;
* [[Database Hardware]]&lt;br /&gt;
* [[Reliable Writes]]&lt;br /&gt;
&lt;br /&gt;
==Benchmark Workloads== &lt;br /&gt;
* [[:Category:Benchmarking]]&lt;br /&gt;
&lt;br /&gt;
[[Category:Administration]][[Category:Performance]]&lt;br /&gt;
[[Category:General articles and guides]]&lt;/div&gt;</summary>
		<author><name>Natmaka</name></author>
	</entry>
	<entry>
		<id>https://wiki.postgresql.org/index.php?title=Working_with_Dates_and_Times_in_PostgreSQL&amp;diff=14314</id>
		<title>Working with Dates and Times in PostgreSQL</title>
		<link rel="alternate" type="text/html" href="https://wiki.postgresql.org/index.php?title=Working_with_Dates_and_Times_in_PostgreSQL&amp;diff=14314"/>
		<updated>2011-05-12T13:45:02Z</updated>

		<summary type="html">&lt;p&gt;Natmaka: /* I need to display a DATE as text, or convert text into a DATE or INTERVAL */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;by Josh Berkus&lt;br /&gt;
&lt;br /&gt;
This FAQ is intended to answer the following questions:&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Q: Where are the DATEADD() and DATEDIFF() functions in PostgreSQL?&#039;&#039;&#039;&amp;lt;br&amp;gt;&lt;br /&gt;
&#039;&#039;&#039;Q: How do I tell the amount of time between X and Y?&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
KEYWORDS: date, datetime, timestamp, operator, dateadd, datediff, interval&lt;br /&gt;
&lt;br /&gt;
=== First, the legalese ===&lt;br /&gt;
&lt;br /&gt;
Copyright 2001 Josh Berkus (http://www.agliodbs.com).  Permission granted to use in any public forum for which no fee is charged if this copyright notice appears in the document, or alternately in any published for-fee work if 1% or more of the proceeds of such work are donated or paid to benefit PostgreSQL development.  This advice is provided with no warranty whatsoever, including any warranty of fitness for a particular purpose.  Use at your own risk.&lt;br /&gt;
&lt;br /&gt;
=== INTRODUCTION ===&lt;br /&gt;
One of PostgreSQL&#039;s joys is a robust support of a variety of date and time data types and their associated operators.  This has allowed me to write calendaring applications in PostgreSQL that would have been considerably more difficult on other platforms.&lt;br /&gt;
&lt;br /&gt;
Before we get down to the nuts-and-bolts, I need to explain a few things to the many who have come to us from database applications which are less ANSI 92 SQL compliant than PostgreSQL (particularly Microsoft SQL Server, SyBase and Microsoft Access).  If you are already educated, you&#039;ll want to skip down to &amp;quot;Working with DATETIME, DATE, and INTERVAL values&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
(BTW, I am not on an anti-Microsoft tirade here.  I use MS SQL Server as an example of a non-standards-compliant database because I am a certified MS SQL Server admin and know its problems quite well.  There are plenty of other non-compliant databases on the market.)&lt;br /&gt;
&lt;br /&gt;
=== ANSI SQL and OPERATORS ===&lt;br /&gt;
&lt;br /&gt;
In the ANSI SQL world, operators (such as + - * % || !) are defined only in the context of the data types being operated upon.  Thus the division of two integers ( INT / INT ) does not function in the same way as the division of two float values (FLOAT / FLOAT).  More dramatically, you may subtract one integer (INT - INT) from another, but you may not subtract one string from another (VARCHAR - VARCHAR), let alone subtract a string from an integer (INT - VARCHAR).  The subtraction operator (-) in these two operations, while it looks the same, is in fact not the same owing to a different datatype context.  In the absence of a predefined context, the operator does not function at all and you get an error message.&lt;br /&gt;
&lt;br /&gt;
This fundamental rule has a number of tedious consequences.  Frequently you must CAST two values to the same data type in order to work with them.  For example, try adding a FLOAT and a NUMERIC value; you will get an error until you help out the database by defining them both as FLOAT or both as NUMERIC (CAST(FLOAT AS NUMERIC) + NUMERIC).  Even more so, appending an integer to the end of a string requires a type conversion function (to_char(INT, &#039;00000&#039;)).  Further, if you want to define your own data types, you must spend the hours necessary to define all possible operators for them as well.&lt;br /&gt;
&lt;br /&gt;
Some database developers, in a rush to get their products to market, saw the above &amp;quot;user-unfriendly&amp;quot; behaviour and cut it out of the system by defining all operators to work in a context-insensitive way.  Thus, in Microsoft Transact-SQL, you may add a DOUBLE and an INTEGER, or even append an INTEGER directly to a string in some cases.  The database can handle the implicit conversions for you, because they have been simplified.&lt;br /&gt;
&lt;br /&gt;
However, the Transact-SQL developers disregarded the essential reason for including context-sensitive operators into the SQL standard.  Only with real, context-sensitive operators can you handle special data types that do not follow arithmetic or concatenation rules.  PostgreSQL&#039;s ability to handle IP addresses, geometric shapes, and, most importantly for our discussion, dates and times, is dependant on this robust operator implementation.  Non-compliant dialects of SQL, such as Transact-SQL, are forced to resort to proprietary functions like DATEADD() and DATEDIFF() in order to work with dates and times, and cannot handle more complex data types at all.&lt;br /&gt;
&lt;br /&gt;
Thus, to answer the first question :&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Q. Where are the DATEADD and DATEDIFF functions in PostgreSQL?&#039;&#039;&#039;&amp;lt;br&amp;gt;&lt;br /&gt;
&#039;&#039;&#039;A.&#039;&#039;&#039; There are none.  PostgreSQL does not need them.  Use the + and - operators instead.  Read on.&lt;br /&gt;
&lt;br /&gt;
=== WORKING with DATETIME, DATE, and INTERVAL VALUES ===&lt;br /&gt;
&lt;br /&gt;
[http://www.postgresql.org/docs/current/interactive/datatype-datetime.html Complete docs on date/time data types exist], I will not attempt to reproduce them here.  Instead, I will simply try to explain to the beginner what you need to know to actually work with dates, times, and intervals.&lt;br /&gt;
&lt;br /&gt;
==== Types ====&lt;br /&gt;
&lt;br /&gt;
;DATETIME or TIMESTAMP:Structured &amp;quot;real&amp;quot; date and time values, containing year, month, day, hour, minute, second and millisecond for all useful date &amp;amp; time values (4713 BC to over 100,000 AD).&lt;br /&gt;
&lt;br /&gt;
;DATE:Simplified integer-based representation of a date defining only year, month, and day.&lt;br /&gt;
&lt;br /&gt;
;INTERVAL:Structured value showing a period of time, including any/all of years, months, weeks, days, hours, minutes, seconds, and milliseconds.  &amp;quot;1 day&amp;quot;, &amp;quot;42 minutes 10 seconds&amp;quot;, and &amp;quot;2 years&amp;quot; are all INTERVAL values.&lt;br /&gt;
&lt;br /&gt;
==== What about TIMESTAMP WITH TIME ZONE? ====&lt;br /&gt;
&lt;br /&gt;
An important topic, that I don&#039;t want to get into here.  Eventually someone will document this.  Suffice it to say that all TIMESTAMP values carry TIMEZONE data as well which you may safely ignore if you don&#039;t need to handle different time zones.&lt;br /&gt;
&lt;br /&gt;
==== Which do I want to use: DATE or TIMESTAMP?  I don&#039;t need minutes or hours in my value ====&lt;br /&gt;
&lt;br /&gt;
That depends.  DATE is easier to work with for arithmetic (e.g. something reoccurring at a random interval of days), takes less storage space, and doesn&#039;t trail &amp;quot;00:00:00&amp;quot; strings you don&#039;t need when printed.  However, TIMESTAMP is far better for real calendar calculations (e.g. something that happens on the 15th of each month or the 2nd Thursday of leap years).  More below.&lt;br /&gt;
&lt;br /&gt;
Now, to work with TIMESTAMP and INTERVAL, you need to understand these few simple rules :&lt;br /&gt;
&lt;br /&gt;
===== 1. The difference between two TIMESTAMPs is always an INTERVAL =====&lt;br /&gt;
&lt;br /&gt;
 TIMESTAMP &#039;1999-12-30&#039; - TIMESTAMP &#039;1999-12-11&#039; = INTERVAL &#039;19 days&#039;&lt;br /&gt;
&lt;br /&gt;
===== 2. You may add or subtract an INTERVAL to a TIMESTAMP to produce another TIMESTAMP =====&lt;br /&gt;
&lt;br /&gt;
TIMESTAMP &#039;1999-12-11&#039; + INTERVAL &#039;19 days&#039; = TIMESTAMP &#039;1999-12-30&#039;&lt;br /&gt;
&lt;br /&gt;
===== 3. You may add or subtract two INTERVALS =====&lt;br /&gt;
&lt;br /&gt;
 INTERVAL &#039;1 month&#039; + INTERVAL &#039;1 month 3 days&#039; = INTERVAL &#039;2 months 3 days&#039;&lt;br /&gt;
&lt;br /&gt;
===== 4. Multiplication and division of INTERVALS is under development and discussion at this time =====&lt;br /&gt;
&lt;br /&gt;
It is suggested that you avoid it until implementation is complete or you may get unexpected results.&lt;br /&gt;
&lt;br /&gt;
===== 5. You may NOT (ever) perform Addition, Multiplication, or Division operations with two TIMESTAMPS =====&lt;br /&gt;
&lt;br /&gt;
 TIMESTAMP &#039;2001-03-24&#039; + TIMESTAMP &#039;2001-10-01&#039; = OPERATION ERROR&lt;br /&gt;
&lt;br /&gt;
===== 6. Many larger INTERVAL values, like the calendar values they reflect, are &#039;&#039;&#039;not constant&#039;&#039;&#039; in length when expressed in smaller INTERVAL values =====&lt;br /&gt;
&lt;br /&gt;
For example (differences bolded):&lt;br /&gt;
&lt;br /&gt;
TIMESTAMP &#039;2001-0&#039;&#039;&#039;7&#039;&#039;&#039;-02&#039; + INTERVAL &#039;1 month&#039; = TIMESTAMP &#039;2001-08-02&#039;&amp;lt;br&amp;gt;&lt;br /&gt;
TIMESTAMP &#039;2001-0&#039;&#039;&#039;7&#039;&#039;&#039;-02&#039; + INTERVAL &#039;31 days&#039; = TIMESTAMP &#039;2001-08-0&#039;&#039;&#039;2&#039;&#039;&#039;&#039;&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;but:&#039;&#039;&#039;&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
TIMESTAMP &#039;2001-0&#039;&#039;&#039;2&#039;&#039;&#039;-02&#039; + INTERVAL &#039;1 month&#039; = TIMESTAMP &#039;2001-03-02&#039;&amp;lt;br&amp;gt;&lt;br /&gt;
TIMESTAMP &#039;2001-0&#039;&#039;&#039;2&#039;&#039;&#039;-02&#039; + INTERVAL &#039;31&#039; days&#039; = TIMESTAMP &#039;2001-03-0&#039;&#039;&#039;5&#039;&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This makes the TIMESTAMP/INTERVAL combination ideal, for example, for scheduling an event which must reoccur every month on the 8th regardless of the length of the month, but problematic if you are trying to figure out the number of days in the last 3.5 months.  Keep it in mind!&lt;br /&gt;
&lt;br /&gt;
The DATE datatype, however, is simpler to deal with if less powerful.&lt;br /&gt;
&lt;br /&gt;
==== Operations with DATEs ====&lt;br /&gt;
&lt;br /&gt;
===== 1. The difference between two DATES is always an INTEGER, representing the number of DAYS difference =====&lt;br /&gt;
&lt;br /&gt;
 DATE &#039;1999-12-30&#039; - DATE &#039;1999-12-11&#039; = INTEGER 19&lt;br /&gt;
&lt;br /&gt;
===== You may add or subtract an INTEGER to a DATE to produce another DATE =====&lt;br /&gt;
&lt;br /&gt;
 DATE &#039;1999-12-11&#039; + INTEGER 19 = DATE &#039;1999-12-30&#039;&lt;br /&gt;
&lt;br /&gt;
===== Because the difference of two DATES is an INTEGER, this difference may be added, subtracted, divided, multiplied, or even modulo (%) =====&lt;br /&gt;
&lt;br /&gt;
===== As with TIMESTAMP, you may NOT perform Addition, Multiplication, Division, or other operations with two DATES =====&lt;br /&gt;
&lt;br /&gt;
===== DATE/INTEGER cannot figure out the varying lengths of months and years =====&lt;br /&gt;
&lt;br /&gt;
Because DATE differences are always calculated as whole numbers of days, DATE/INTEGER cannot figure out the varying lengths of months and years.  Thus, you cannot use DATE/INTEGER to schedule something for the 5th of every month without some very fancy length-of-month calculating on the fly.  This makes DATE ideal for calendar applications involving a lot of calculating based on numbers of days (e.g. &amp;quot;For how many 14-day periods has employee &amp;quot;x&amp;quot; been employed?&amp;quot;) but poor for actual calendaring apps.  Keep it in mind.&lt;br /&gt;
&lt;br /&gt;
==== I&#039;m porting an app from MS SQL Server, and I need to support the DATEDIFF and DATEADD functions so that my stored views will work ====&lt;br /&gt;
&lt;br /&gt;
Proceed to PostgreSQL TechDocs (http://techdocs.postgresql.org).  There are many porting resources there, and I&#039;d be surprised if someone hasn&#039;t already re-created these functions under PostgreSQL.&lt;br /&gt;
&lt;br /&gt;
==== I need to display a DATE as text, or convert text into a DATE or INTERVAL ====&lt;br /&gt;
&lt;br /&gt;
You want the [http://www.postgresql.org/docs/current/interactive/functions-formatting.html to_date(), to_char()], and [http://www.postgresql.org/docs/current/interactive/functions-datetime.html interval()] functions.&lt;br /&gt;
&lt;br /&gt;
==== What if I want to get the month as an integer out of a date?====&lt;br /&gt;
&lt;br /&gt;
You want the [http://www.postgresql.org/docs/current/interactive/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT extract()] function.  This function also works to give you other numeric intervals from a timestamp, including the Unix system datetime (e.g. EXTRACT ( epoch from some_date ))&lt;/div&gt;</summary>
		<author><name>Natmaka</name></author>
	</entry>
	<entry>
		<id>https://wiki.postgresql.org/index.php?title=Working_with_Dates_and_Times_in_PostgreSQL&amp;diff=14313</id>
		<title>Working with Dates and Times in PostgreSQL</title>
		<link rel="alternate" type="text/html" href="https://wiki.postgresql.org/index.php?title=Working_with_Dates_and_Times_in_PostgreSQL&amp;diff=14313"/>
		<updated>2011-05-12T13:40:55Z</updated>

		<summary type="html">&lt;p&gt;Natmaka: /* What if I want to get the month as an integer out of a date? */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;by Josh Berkus&lt;br /&gt;
&lt;br /&gt;
This FAQ is intended to answer the following questions:&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Q: Where are the DATEADD() and DATEDIFF() functions in PostgreSQL?&#039;&#039;&#039;&amp;lt;br&amp;gt;&lt;br /&gt;
&#039;&#039;&#039;Q: How do I tell the amount of time between X and Y?&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
KEYWORDS: date, datetime, timestamp, operator, dateadd, datediff, interval&lt;br /&gt;
&lt;br /&gt;
=== First, the legalese ===&lt;br /&gt;
&lt;br /&gt;
Copyright 2001 Josh Berkus (http://www.agliodbs.com).  Permission granted to use in any public forum for which no fee is charged if this copyright notice appears in the document, or alternately in any published for-fee work if 1% or more of the proceeds of such work are donated or paid to benefit PostgreSQL development.  This advice is provided with no warranty whatsoever, including any warranty of fitness for a particular purpose.  Use at your own risk.&lt;br /&gt;
&lt;br /&gt;
=== INTRODUCTION ===&lt;br /&gt;
One of PostgreSQL&#039;s joys is a robust support of a variety of date and time data types and their associated operators.  This has allowed me to write calendaring applications in PostgreSQL that would have been considerably more difficult on other platforms.&lt;br /&gt;
&lt;br /&gt;
Before we get down to the nuts-and-bolts, I need to explain a few things to the many who have come to us from database applications which are less ANSI 92 SQL compliant than PostgreSQL (particularly Microsoft SQL Server, SyBase and Microsoft Access).  If you are already educated, you&#039;ll want to skip down to &amp;quot;Working with DATETIME, DATE, and INTERVAL values&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
(BTW, I am not on an anti-Microsoft tirade here.  I use MS SQL Server as an example of a non-standards-compliant database because I am a certified MS SQL Server admin and know its problems quite well.  There are plenty of other non-compliant databases on the market.)&lt;br /&gt;
&lt;br /&gt;
=== ANSI SQL and OPERATORS ===&lt;br /&gt;
&lt;br /&gt;
In the ANSI SQL world, operators (such as + - * % || !) are defined only in the context of the data types being operated upon.  Thus the division of two integers ( INT / INT ) does not function in the same way as the division of two float values (FLOAT / FLOAT).  More dramatically, you may subtract one integer (INT - INT) from another, but you may not subtract one string from another (VARCHAR - VARCHAR), let alone subtract a string from an integer (INT - VARCHAR).  The subtraction operator (-) in these two operations, while it looks the same, is in fact not the same owing to a different datatype context.  In the absence of a predefined context, the operator does not function at all and you get an error message.&lt;br /&gt;
&lt;br /&gt;
This fundamental rule has a number of tedious consequences.  Frequently you must CAST two values to the same data type in order to work with them.  For example, try adding a FLOAT and a NUMERIC value; you will get an error until you help out the database by defining them both as FLOAT or both as NUMERIC (CAST(FLOAT AS NUMERIC) + NUMERIC).  Even more so, appending an integer to the end of a string requires a type conversion function (to_char(INT, &#039;00000&#039;)).  Further, if you want to define your own data types, you must spend the hours necessary to define all possible operators for them as well.&lt;br /&gt;
&lt;br /&gt;
Some database developers, in a rush to get their products to market, saw the above &amp;quot;user-unfriendly&amp;quot; behaviour and cut it out of the system by defining all operators to work in a context-insensitive way.  Thus, in Microsoft Transact-SQL, you may add a DOUBLE and an INTEGER, or even append an INTEGER directly to a string in some cases.  The database can handle the implicit conversions for you, because they have been simplified.&lt;br /&gt;
&lt;br /&gt;
However, the Transact-SQL developers disregarded the essential reason for including context-sensitive operators into the SQL standard.  Only with real, context-sensitive operators can you handle special data types that do not follow arithmetic or concatenation rules.  PostgreSQL&#039;s ability to handle IP addresses, geometric shapes, and, most importantly for our discussion, dates and times, is dependant on this robust operator implementation.  Non-compliant dialects of SQL, such as Transact-SQL, are forced to resort to proprietary functions like DATEADD() and DATEDIFF() in order to work with dates and times, and cannot handle more complex data types at all.&lt;br /&gt;
&lt;br /&gt;
Thus, to answer the first question :&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Q. Where are the DATEADD and DATEDIFF functions in PostgreSQL?&#039;&#039;&#039;&amp;lt;br&amp;gt;&lt;br /&gt;
&#039;&#039;&#039;A.&#039;&#039;&#039; There are none.  PostgreSQL does not need them.  Use the + and - operators instead.  Read on.&lt;br /&gt;
&lt;br /&gt;
=== WORKING with DATETIME, DATE, and INTERVAL VALUES ===&lt;br /&gt;
&lt;br /&gt;
[http://www.postgresql.org/docs/current/interactive/datatype-datetime.html Complete docs on date/time data types exist], I will not attempt to reproduce them here.  Instead, I will simply try to explain to the beginner what you need to know to actually work with dates, times, and intervals.&lt;br /&gt;
&lt;br /&gt;
==== Types ====&lt;br /&gt;
&lt;br /&gt;
;DATETIME or TIMESTAMP:Structured &amp;quot;real&amp;quot; date and time values, containing year, month, day, hour, minute, second and millisecond for all useful date &amp;amp; time values (4713 BC to over 100,000 AD).&lt;br /&gt;
&lt;br /&gt;
;DATE:Simplified integer-based representation of a date defining only year, month, and day.&lt;br /&gt;
&lt;br /&gt;
;INTERVAL:Structured value showing a period of time, including any/all of years, months, weeks, days, hours, minutes, seconds, and milliseconds.  &amp;quot;1 day&amp;quot;, &amp;quot;42 minutes 10 seconds&amp;quot;, and &amp;quot;2 years&amp;quot; are all INTERVAL values.&lt;br /&gt;
&lt;br /&gt;
==== What about TIMESTAMP WITH TIME ZONE? ====&lt;br /&gt;
&lt;br /&gt;
An important topic, that I don&#039;t want to get into here.  Eventually someone will document this.  Suffice it to say that all TIMESTAMP values carry TIMEZONE data as well which you may safely ignore if you don&#039;t need to handle different time zones.&lt;br /&gt;
&lt;br /&gt;
==== Which do I want to use: DATE or TIMESTAMP?  I don&#039;t need minutes or hours in my value ====&lt;br /&gt;
&lt;br /&gt;
That depends.  DATE is easier to work with for arithmetic (e.g. something reoccurring at a random interval of days), takes less storage space, and doesn&#039;t trail &amp;quot;00:00:00&amp;quot; strings you don&#039;t need when printed.  However, TIMESTAMP is far better for real calendar calculations (e.g. something that happens on the 15th of each month or the 2nd Thursday of leap years).  More below.&lt;br /&gt;
&lt;br /&gt;
Now, to work with TIMESTAMP and INTERVAL, you need to understand these few simple rules :&lt;br /&gt;
&lt;br /&gt;
===== 1. The difference between two TIMESTAMPs is always an INTERVAL =====&lt;br /&gt;
&lt;br /&gt;
 TIMESTAMP &#039;1999-12-30&#039; - TIMESTAMP &#039;1999-12-11&#039; = INTERVAL &#039;19 days&#039;&lt;br /&gt;
&lt;br /&gt;
===== 2. You may add or subtract an INTERVAL to a TIMESTAMP to produce another TIMESTAMP =====&lt;br /&gt;
&lt;br /&gt;
TIMESTAMP &#039;1999-12-11&#039; + INTERVAL &#039;19 days&#039; = TIMESTAMP &#039;1999-12-30&#039;&lt;br /&gt;
&lt;br /&gt;
===== 3. You may add or subtract two INTERVALS =====&lt;br /&gt;
&lt;br /&gt;
 INTERVAL &#039;1 month&#039; + INTERVAL &#039;1 month 3 days&#039; = INTERVAL &#039;2 months 3 days&#039;&lt;br /&gt;
&lt;br /&gt;
===== 4. Multiplication and division of INTERVALS is under development and discussion at this time =====&lt;br /&gt;
&lt;br /&gt;
It is suggested that you avoid it until implementation is complete or you may get unexpected results.&lt;br /&gt;
&lt;br /&gt;
===== 5. You may NOT (ever) perform Addition, Multiplication, or Division operations with two TIMESTAMPS =====&lt;br /&gt;
&lt;br /&gt;
 TIMESTAMP &#039;2001-03-24&#039; + TIMESTAMP &#039;2001-10-01&#039; = OPERATION ERROR&lt;br /&gt;
&lt;br /&gt;
===== 6. Many larger INTERVAL values, like the calendar values they reflect, are &#039;&#039;&#039;not constant&#039;&#039;&#039; in length when expressed in smaller INTERVAL values =====&lt;br /&gt;
&lt;br /&gt;
For example (differences bolded):&lt;br /&gt;
&lt;br /&gt;
TIMESTAMP &#039;2001-0&#039;&#039;&#039;7&#039;&#039;&#039;-02&#039; + INTERVAL &#039;1 month&#039; = TIMESTAMP &#039;2001-08-02&#039;&amp;lt;br&amp;gt;&lt;br /&gt;
TIMESTAMP &#039;2001-0&#039;&#039;&#039;7&#039;&#039;&#039;-02&#039; + INTERVAL &#039;31 days&#039; = TIMESTAMP &#039;2001-08-0&#039;&#039;&#039;2&#039;&#039;&#039;&#039;&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;but:&#039;&#039;&#039;&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
TIMESTAMP &#039;2001-0&#039;&#039;&#039;2&#039;&#039;&#039;-02&#039; + INTERVAL &#039;1 month&#039; = TIMESTAMP &#039;2001-03-02&#039;&amp;lt;br&amp;gt;&lt;br /&gt;
TIMESTAMP &#039;2001-0&#039;&#039;&#039;2&#039;&#039;&#039;-02&#039; + INTERVAL &#039;31&#039; days&#039; = TIMESTAMP &#039;2001-03-0&#039;&#039;&#039;5&#039;&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This makes the TIMESTAMP/INTERVAL combination ideal, for example, for scheduling an event which must reoccur every month on the 8th regardless of the length of the month, but problematic if you are trying to figure out the number of days in the last 3.5 months.  Keep it in mind!&lt;br /&gt;
&lt;br /&gt;
The DATE datatype, however, is simpler to deal with if less powerful.&lt;br /&gt;
&lt;br /&gt;
==== Operations with DATEs ====&lt;br /&gt;
&lt;br /&gt;
===== 1. The difference between two DATES is always an INTEGER, representing the number of DAYS difference =====&lt;br /&gt;
&lt;br /&gt;
 DATE &#039;1999-12-30&#039; - DATE &#039;1999-12-11&#039; = INTEGER 19&lt;br /&gt;
&lt;br /&gt;
===== You may add or subtract an INTEGER to a DATE to produce another DATE =====&lt;br /&gt;
&lt;br /&gt;
 DATE &#039;1999-12-11&#039; + INTEGER 19 = DATE &#039;1999-12-30&#039;&lt;br /&gt;
&lt;br /&gt;
===== Because the difference of two DATES is an INTEGER, this difference may be added, subtracted, divided, multiplied, or even modulo (%) =====&lt;br /&gt;
&lt;br /&gt;
===== As with TIMESTAMP, you may NOT perform Addition, Multiplication, Division, or other operations with two DATES =====&lt;br /&gt;
&lt;br /&gt;
===== DATE/INTEGER cannot figure out the varying lengths of months and years =====&lt;br /&gt;
&lt;br /&gt;
Because DATE differences are always calculated as whole numbers of days, DATE/INTEGER cannot figure out the varying lengths of months and years.  Thus, you cannot use DATE/INTEGER to schedule something for the 5th of every month without some very fancy length-of-month calculating on the fly.  This makes DATE ideal for calendar applications involving a lot of calculating based on numbers of days (e.g. &amp;quot;For how many 14-day periods has employee &amp;quot;x&amp;quot; been employed?&amp;quot;) but poor for actual calendaring apps.  Keep it in mind.&lt;br /&gt;
&lt;br /&gt;
==== I&#039;m porting an app from MS SQL Server, and I need to support the DATEDIFF and DATEADD functions so that my stored views will work ====&lt;br /&gt;
&lt;br /&gt;
Proceed to PostgreSQL TechDocs (http://techdocs.postgresql.org).  There are many porting resources there, and I&#039;d be surprised if someone hasn&#039;t already re-created these functions under PostgreSQL.&lt;br /&gt;
&lt;br /&gt;
==== I need to display a DATE as text, or convert text into a DATE or INTERVAL ====&lt;br /&gt;
&lt;br /&gt;
You want the to_date(), to_char(), and interval() functions.  See &amp;quot;functions and operators&amp;quot; in the PostgreSQL docs: http://www.postgresql.org/docs/current/interactive/functions.html&lt;br /&gt;
&lt;br /&gt;
==== What if I want to get the month as an integer out of a date?====&lt;br /&gt;
&lt;br /&gt;
You want the [http://www.postgresql.org/docs/current/interactive/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT extract()] function.  This function also works to give you other numeric intervals from a timestamp, including the Unix system datetime (e.g. EXTRACT ( epoch from some_date ))&lt;/div&gt;</summary>
		<author><name>Natmaka</name></author>
	</entry>
	<entry>
		<id>https://wiki.postgresql.org/index.php?title=User:Natmaka&amp;diff=14312</id>
		<title>User:Natmaka</title>
		<link rel="alternate" type="text/html" href="https://wiki.postgresql.org/index.php?title=User:Natmaka&amp;diff=14312"/>
		<updated>2011-05-12T12:45:13Z</updated>

		<summary type="html">&lt;p&gt;Natmaka: Created page with &amp;quot;[http://makarevitch.org Nat Makarevitch]&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[http://makarevitch.org Nat Makarevitch]&lt;/div&gt;</summary>
		<author><name>Natmaka</name></author>
	</entry>
	<entry>
		<id>https://wiki.postgresql.org/index.php?title=Working_with_Dates_and_Times_in_PostgreSQL&amp;diff=14311</id>
		<title>Working with Dates and Times in PostgreSQL</title>
		<link rel="alternate" type="text/html" href="https://wiki.postgresql.org/index.php?title=Working_with_Dates_and_Times_in_PostgreSQL&amp;diff=14311"/>
		<updated>2011-05-12T12:44:44Z</updated>

		<summary type="html">&lt;p&gt;Natmaka: /* WORKING with DATETIME, DATE, and INTERVAL VALUES */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;by Josh Berkus&lt;br /&gt;
&lt;br /&gt;
This FAQ is intended to answer the following questions:&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Q: Where are the DATEADD() and DATEDIFF() functions in PostgreSQL?&#039;&#039;&#039;&amp;lt;br&amp;gt;&lt;br /&gt;
&#039;&#039;&#039;Q: How do I tell the amount of time between X and Y?&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
KEYWORDS: date, datetime, timestamp, operator, dateadd, datediff, interval&lt;br /&gt;
&lt;br /&gt;
=== First, the legalese ===&lt;br /&gt;
&lt;br /&gt;
Copyright 2001 Josh Berkus (http://www.agliodbs.com).  Permission granted to use in any public forum for which no fee is charged if this copyright notice appears in the document, or alternately in any published for-fee work if 1% or more of the proceeds of such work are donated or paid to benefit PostgreSQL development.  This advice is provided with no warranty whatsoever, including any warranty of fitness for a particular purpose.  Use at your own risk.&lt;br /&gt;
&lt;br /&gt;
=== INTRODUCTION ===&lt;br /&gt;
One of PostgreSQL&#039;s joys is a robust support of a variety of date and time data types and their associated operators.  This has allowed me to write calendaring applications in PostgreSQL that would have been considerably more difficult on other platforms.&lt;br /&gt;
&lt;br /&gt;
Before we get down to the nuts-and-bolts, I need to explain a few things to the many who have come to us from database applications which are less ANSI 92 SQL compliant than PostgreSQL (particularly Microsoft SQL Server, SyBase and Microsoft Access).  If you are already educated, you&#039;ll want to skip down to &amp;quot;Working with DATETIME, DATE, and INTERVAL values&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
(BTW, I am not on an anti-Microsoft tirade here.  I use MS SQL Server as an example of a non-standards-compliant database because I am a certified MS SQL Server admin and know its problems quite well.  There are plenty of other non-compliant databases on the market.)&lt;br /&gt;
&lt;br /&gt;
=== ANSI SQL and OPERATORS ===&lt;br /&gt;
&lt;br /&gt;
In the ANSI SQL world, operators (such as + - * % || !) are defined only in the context of the data types being operated upon.  Thus the division of two integers ( INT / INT ) does not function in the same way as the division of two float values (FLOAT / FLOAT).  More dramatically, you may subtract one integer (INT - INT) from another, but you may not subtract one string from another (VARCHAR - VARCHAR), let alone subtract a string from an integer (INT - VARCHAR).  The subtraction operator (-) in these two operations, while it looks the same, is in fact not the same owing to a different datatype context.  In the absence of a predefined context, the operator does not function at all and you get an error message.&lt;br /&gt;
&lt;br /&gt;
This fundamental rule has a number of tedious consequences.  Frequently you must CAST two values to the same data type in order to work with them.  For example, try adding a FLOAT and a NUMERIC value; you will get an error until you help out the database by defining them both as FLOAT or both as NUMERIC (CAST(FLOAT AS NUMERIC) + NUMERIC).  Even more so, appending an integer to the end of a string requires a type conversion function (to_char(INT, &#039;00000&#039;)).  Further, if you want to define your own data types, you must spend the hours necessary to define all possible operators for them as well.&lt;br /&gt;
&lt;br /&gt;
Some database developers, in a rush to get their products to market, saw the above &amp;quot;user-unfriendly&amp;quot; behaviour and cut it out of the system by defining all operators to work in a context-insensitive way.  Thus, in Microsoft Transact-SQL, you may add a DOUBLE and an INTEGER, or even append an INTEGER directly to a string in some cases.  The database can handle the implicit conversions for you, because they have been simplified.&lt;br /&gt;
&lt;br /&gt;
However, the Transact-SQL developers disregarded the essential reason for including context-sensitive operators into the SQL standard.  Only with real, context-sensitive operators can you handle special data types that do not follow arithmetic or concatenation rules.  PostgreSQL&#039;s ability to handle IP addresses, geometric shapes, and, most importantly for our discussion, dates and times, is dependant on this robust operator implementation.  Non-compliant dialects of SQL, such as Transact-SQL, are forced to resort to proprietary functions like DATEADD() and DATEDIFF() in order to work with dates and times, and cannot handle more complex data types at all.&lt;br /&gt;
&lt;br /&gt;
Thus, to answer the first question :&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Q. Where are the DATEADD and DATEDIFF functions in PostgreSQL?&#039;&#039;&#039;&amp;lt;br&amp;gt;&lt;br /&gt;
&#039;&#039;&#039;A.&#039;&#039;&#039; There are none.  PostgreSQL does not need them.  Use the + and - operators instead.  Read on.&lt;br /&gt;
&lt;br /&gt;
=== WORKING with DATETIME, DATE, and INTERVAL VALUES ===&lt;br /&gt;
&lt;br /&gt;
[http://www.postgresql.org/docs/current/interactive/datatype-datetime.html Complete docs on date/time data types exist], I will not attempt to reproduce them here.  Instead, I will simply try to explain to the beginner what you need to know to actually work with dates, times, and intervals.&lt;br /&gt;
&lt;br /&gt;
==== Types ====&lt;br /&gt;
&lt;br /&gt;
;DATETIME or TIMESTAMP:Structured &amp;quot;real&amp;quot; date and time values, containing year, month, day, hour, minute, second and millisecond for all useful date &amp;amp; time values (4713 BC to over 100,000 AD).&lt;br /&gt;
&lt;br /&gt;
;DATE:Simplified integer-based representation of a date defining only year, month, and day.&lt;br /&gt;
&lt;br /&gt;
;INTERVAL:Structured value showing a period of time, including any/all of years, months, weeks, days, hours, minutes, seconds, and milliseconds.  &amp;quot;1 day&amp;quot;, &amp;quot;42 minutes 10 seconds&amp;quot;, and &amp;quot;2 years&amp;quot; are all INTERVAL values.&lt;br /&gt;
&lt;br /&gt;
==== What about TIMESTAMP WITH TIME ZONE? ====&lt;br /&gt;
&lt;br /&gt;
An important topic, that I don&#039;t want to get into here.  Eventually someone will document this.  Suffice it to say that all TIMESTAMP values carry TIMEZONE data as well which you may safely ignore if you don&#039;t need to handle different time zones.&lt;br /&gt;
&lt;br /&gt;
==== Which do I want to use: DATE or TIMESTAMP?  I don&#039;t need minutes or hours in my value ====&lt;br /&gt;
&lt;br /&gt;
That depends.  DATE is easier to work with for arithmetic (e.g. something reoccurring at a random interval of days), takes less storage space, and doesn&#039;t trail &amp;quot;00:00:00&amp;quot; strings you don&#039;t need when printed.  However, TIMESTAMP is far better for real calendar calculations (e.g. something that happens on the 15th of each month or the 2nd Thursday of leap years).  More below.&lt;br /&gt;
&lt;br /&gt;
Now, to work with TIMESTAMP and INTERVAL, you need to understand these few simple rules :&lt;br /&gt;
&lt;br /&gt;
===== 1. The difference between two TIMESTAMPs is always an INTERVAL =====&lt;br /&gt;
&lt;br /&gt;
 TIMESTAMP &#039;1999-12-30&#039; - TIMESTAMP &#039;1999-12-11&#039; = INTERVAL &#039;19 days&#039;&lt;br /&gt;
&lt;br /&gt;
===== 2. You may add or subtract an INTERVAL to a TIMESTAMP to produce another TIMESTAMP =====&lt;br /&gt;
&lt;br /&gt;
TIMESTAMP &#039;1999-12-11&#039; + INTERVAL &#039;19 days&#039; = TIMESTAMP &#039;1999-12-30&#039;&lt;br /&gt;
&lt;br /&gt;
===== 3. You may add or subtract two INTERVALS =====&lt;br /&gt;
&lt;br /&gt;
 INTERVAL &#039;1 month&#039; + INTERVAL &#039;1 month 3 days&#039; = INTERVAL &#039;2 months 3 days&#039;&lt;br /&gt;
&lt;br /&gt;
===== 4. Multiplication and division of INTERVALS is under development and discussion at this time =====&lt;br /&gt;
&lt;br /&gt;
It is suggested that you avoid it until implementation is complete or you may get unexpected results.&lt;br /&gt;
&lt;br /&gt;
===== 5. You may NOT (ever) perform Addition, Multiplication, or Division operations with two TIMESTAMPS =====&lt;br /&gt;
&lt;br /&gt;
 TIMESTAMP &#039;2001-03-24&#039; + TIMESTAMP &#039;2001-10-01&#039; = OPERATION ERROR&lt;br /&gt;
&lt;br /&gt;
===== 6. Many larger INTERVAL values, like the calendar values they reflect, are &#039;&#039;&#039;not constant&#039;&#039;&#039; in length when expressed in smaller INTERVAL values =====&lt;br /&gt;
&lt;br /&gt;
For example (differences bolded):&lt;br /&gt;
&lt;br /&gt;
TIMESTAMP &#039;2001-0&#039;&#039;&#039;7&#039;&#039;&#039;-02&#039; + INTERVAL &#039;1 month&#039; = TIMESTAMP &#039;2001-08-02&#039;&amp;lt;br&amp;gt;&lt;br /&gt;
TIMESTAMP &#039;2001-0&#039;&#039;&#039;7&#039;&#039;&#039;-02&#039; + INTERVAL &#039;31 days&#039; = TIMESTAMP &#039;2001-08-0&#039;&#039;&#039;2&#039;&#039;&#039;&#039;&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;but:&#039;&#039;&#039;&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
TIMESTAMP &#039;2001-0&#039;&#039;&#039;2&#039;&#039;&#039;-02&#039; + INTERVAL &#039;1 month&#039; = TIMESTAMP &#039;2001-03-02&#039;&amp;lt;br&amp;gt;&lt;br /&gt;
TIMESTAMP &#039;2001-0&#039;&#039;&#039;2&#039;&#039;&#039;-02&#039; + INTERVAL &#039;31&#039; days&#039; = TIMESTAMP &#039;2001-03-0&#039;&#039;&#039;5&#039;&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
This makes the TIMESTAMP/INTERVAL combination ideal, for example, for scheduling an event which must reoccur every month on the 8th regardless of the length of the month, but problematic if you are trying to figure out the number of days in the last 3.5 months.  Keep it in mind!&lt;br /&gt;
&lt;br /&gt;
The DATE datatype, however, is simpler to deal with if less powerful.&lt;br /&gt;
&lt;br /&gt;
==== Operations with DATEs ====&lt;br /&gt;
&lt;br /&gt;
===== 1. The difference between two DATES is always an INTEGER, representing the number of DAYS difference =====&lt;br /&gt;
&lt;br /&gt;
 DATE &#039;1999-12-30&#039; - DATE &#039;1999-12-11&#039; = INTEGER 19&lt;br /&gt;
&lt;br /&gt;
===== You may add or subtract an INTEGER to a DATE to produce another DATE =====&lt;br /&gt;
&lt;br /&gt;
 DATE &#039;1999-12-11&#039; + INTEGER 19 = DATE &#039;1999-12-30&#039;&lt;br /&gt;
&lt;br /&gt;
===== Because the difference of two DATES is an INTEGER, this difference may be added, subtracted, divided, multiplied, or even modulo (%) =====&lt;br /&gt;
&lt;br /&gt;
===== As with TIMESTAMP, you may NOT perform Addition, Multiplication, Division, or other operations with two DATES =====&lt;br /&gt;
&lt;br /&gt;
===== DATE/INTEGER cannot figure out the varying lengths of months and years =====&lt;br /&gt;
&lt;br /&gt;
Because DATE differences are always calculated as whole numbers of days, DATE/INTEGER cannot figure out the varying lengths of months and years.  Thus, you cannot use DATE/INTEGER to schedule something for the 5th of every month without some very fancy length-of-month calculating on the fly.  This makes DATE ideal for calendar applications involving a lot of calculating based on numbers of days (e.g. &amp;quot;For how many 14-day periods has employee &amp;quot;x&amp;quot; been employed?&amp;quot;) but poor for actual calendaring apps.  Keep it in mind.&lt;br /&gt;
&lt;br /&gt;
==== I&#039;m porting an app from MS SQL Server, and I need to support the DATEDIFF and DATEADD functions so that my stored views will work ====&lt;br /&gt;
&lt;br /&gt;
Proceed to PostgreSQL TechDocs (http://techdocs.postgresql.org).  There are many porting resources there, and I&#039;d be surprised if someone hasn&#039;t already re-created these functions under PostgreSQL.&lt;br /&gt;
&lt;br /&gt;
==== I need to display a DATE as text, or convert text into a DATE or INTERVAL ====&lt;br /&gt;
&lt;br /&gt;
You want the to_date(), to_char(), and interval() functions.  See &amp;quot;functions and operators&amp;quot; in the PostgreSQL docs: http://www.postgresql.org/docs/current/interactive/functions.html&lt;br /&gt;
&lt;br /&gt;
==== What if I want to get the month as an integer out of a date?====&lt;br /&gt;
&lt;br /&gt;
You want the extract() function.  This function also works to give you other numeric intervals from a timestamp, including the Unix system datetime (e.g. EXTRACT ( epoch from some_date ))&lt;/div&gt;</summary>
		<author><name>Natmaka</name></author>
	</entry>
</feed>