7

Does PostgreSQL cache execution plan of a view, as it does for stored procedures?

2 Answers2

8

No.

A view is basically a macro - your view definition gets merged with the query against it and then executed.

So:

CREATE VIEW v1 AS SELECT * FROM customers WHERE active;
SELECT * FROM v1 WHERE name LIKE 'A%';

becomes:

SELECT * FROM customers WHERE active AND name LIKE 'A%';
Richard Huxton
  • 21,516
  • 3
  • 39
  • 51
  • 1
    Indeed, caching the execution plan would make little sense. Maybe today you're selecting every row of the view, and tomorrow you're just selecting one. Those queries are going to require entirely different query plans. – Kevin Feb 18 '15 at 21:19
  • 1
    If someone would find a link to support this answer, that would be nice. May it be different for different versions of PostreSQL? – Yevgeniy Afanasyev Oct 10 '17 at 04:41
  • Agreed @YevgeniyAfanasyev, without evidence to support it this is just an opinion – jcollum Jun 12 '23 at 21:16
  • If anyone feels like not trusting me they could, you know, bother to read the official docs instead. It's not like all this isn't covered there. – Richard Huxton Jun 13 '23 at 06:46
4

Postgresql 9.3 introduced Materialised View, which cache the result of the query. You can invalidate that cache by refreshing it.

Example:

CREATE MATERIALIZED VIEW customers_with_revenue AS
  SELECT
    customers.*,
    SUM(invoice_items.amount_in_cents) AS revenue
  FROM customers
    INNER JOIN invoices
      ON customers.id = invoices.customer_id
    INNER JOIN invoice_items
      ON invoices.id = invoice_items.invoice_id
  GROUP BY customers.id ORDER BY revenue DESC;
REFRESH MATERIALIZED VIEW customers_with_revenue;

Source: https://bugfactory.io/blog/caching-expensive-queries-with-materialized-views-in-postgresql/

Sri
  • 242
  • 3
  • 13