Views

Plain View

A view is a database object that is a stored query. A view is a virtual table you can create dynamically using a saved query acting as a virtual table.

  • You can join a view to another table or view

  • You can query a view

  • Regular views don't store any data, but materialised view does

Syntax

CREATE OR REPLACE VIEW view_name AS query

Example 1

CREATE OR REPLACE VIEW v_movie_quick AS
SELECT movie_name,
       movie_length,
       release_date
from movies mv;

-- use just like a normal table
select * from v_movie_quick limit 5;

     movie_name     | movie_length | release_date 
--------------------+--------------+--------------
 A Clockwork Orange |          112 | 1972-02-02
 Apocalypse Now     |          168 | 1979-08-15
 Battle Royale      |          111 | 2001-01-04
 Blade Runner       |          121 | 1982-06-25
 Chungking Express  |          113 | 1996-08-03

Example with JOIN

Managing VIEW

View containing condition

You cannot add, update, delete columns from a view once created for that create a new view, drop the old view and rename the new view back to original

Deleting from view also deletes from the main table

Materialized View

Allows you to

  • store result of a query

  • update data periodically :: manual

  • used to cache result of heavy data

    syntax

If you want to load data into the materialised view at the creation time, you will use WITH DATA

  • cannot change data in materialised view : insert, update and delete

  • advantage of usingmaterialised view : access and update materialised view without locking everyone else out

  • disadvantage of using materialised view if you alter the base table ,

    materialised view must also me alter : delete the old materialised view and create a new one

Last updated

Was this helpful?