Every time we select rows from a view, we actually select from the result of the underlying query. If that query is slow and we need to use it more than once, then it makes sense to run the query once, save its output as a table, and then select the rows from the latter.
This procedure has been available for a long time, and there is a dedicated syntax, CREATE MATERIALIZED VIEW
, which we will describe in this recipe.
Let's create two randomly populated tables, of which one is large:
CREATE TABLE dish ( dish_id SERIAL PRIMARY KEY , dish_description text ); CREATE TABLE eater ( eater_id SERIAL , eating_date date , dish_id int REFERENCES dish (dish_id) ); INSERT INTO dish (dish_description) VALUES ('Lentils'), ('Mango'), ('Plantain'), ('Rice'), ('Tea'); INSERT INTO eater(eating_date, dish_id) SELECT floor(abs(sin(n)) * 365) :: int + date '2014-01-01' , ceil(abs(sin(n :: float * n))*5) :: int FROM generate_series(1,500000) AS rand(n);
Notice that the data...