Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does PostgreSQL cache statements and data?

Tags:

postgresql

In Oracle, SQL statements will be cached in shared_pool, and data which is selected frequently will be cached in db_cache.

What does PostgreSQL do? Will SQL statements and data be cached in shared_buffers?

like image 345
francs Avatar asked Aug 22 '11 01:08

francs


People also ask

How does Postgres cache work?

Postgres manages a “Shared Buffer Cache”, which it allocates and uses internally to keep data and indexes in memory. This is usually configured to be about 25% of total system memory for a server running a dedicated Postgres instance, such as all Heroku Postgres instances.

Does PostgreSQL use cache?

Caching is all about storing data in memory (RAM) for faster access at a later point of time. PostgreSQL also utilizes caching of its data in a space called shared_buffers.

Does PSQL cache query results?

PostgreSQL Query Cache, a new open source software, which enables to improve query performance extremely (10x~100x) by caching query results, has been launched. PostgreSQL Query Cache: waits connections on the different port from the clients. delegates queries in front of the backends, like a proxy.


1 Answers

Generally, only the contents of table and index files will be cached in the shared buffer space.

Query plans are cached in some circumstances. The best way to ensure this is to PREPARE the query once, then EXECUTE it each time.

The results of a query are not automatically cached. If you rerun the same query -- even if it's letter-for-letter identical, and no updates have been performed on the DB -- it will still execute the whole plan. It will, of course, make use of any table/index data that's already in the shared buffers cache; so it will not necessarily have to read all the data from disk again.

Update on plan caching

Plan caching is generally done per session. This means only the connection that makes the plan can use the cached version. Other connections have to make and use their own cached versions. This isn't really a performance issue because the saving you get from reusing a plan is almost always miniscule compared to the cost of connecting anyway. (Unless your queries are really complicated.)

It does cache if you use PREPARE: http://www.postgresql.org/docs/current/static/sql-prepare.html

It does cache when the query is in a PL/plSQL function: http://www.postgresql.org/docs/current/static/plpgsql-implementation.html#PLPGSQL-PLAN-CACHING

It does not cache ad-hoc queries entered in psql.

Hopefully someone else can elaborate on any other cases of query plan caching.

like image 60
Edmund Avatar answered Oct 07 '22 21:10

Edmund