This page in other versions: 9.0 / 9.1 / 9.2 / 9.3 / 9.4  |  Development versions: devel  |  Unsupported versions: 7.2 / 7.3 / 7.4 / 8.0 / 8.1 / 8.2 / 8.3 / 8.4

3.2. Views

Refer back to the queries in Section 2.6. Suppose the combined listing of weather records and city location is of particular interest to your application, but you do not want to type the query each time you need it. You can create a view over the query, which gives a name to the query that you can refer to like an ordinary table.

CREATE VIEW myview AS
    SELECT city, temp_lo, temp_hi, prcp, date, location
        FROM weather, cities
        WHERE city = name;

SELECT * FROM myview;

Making liberal use of views is a key aspect of good SQL database design. Views allow you to encapsulate the details of the structure of your tables, which may change as your application evolves, behind consistent interfaces.

Views can be used in almost any place a real table can be used. Building views upon other views is not uncommon.

Comments


Jan. 5, 2005, 3:35 a.m.

Consider the heuristic "Never let your users query your data directly from the tables, only ever through views", and it's companion "Never let your users manilulate your data directly, only ever via stored procedures".

If you follow this advice, then you will have all the benefits of data encapsulation. These include the simplified query composition and interfaces consistency mentioned above, as well as creating a natural choke point which facilitates security. I advocate creating a second tier of views over the 'encapsulating' one (i.e. over the stable API) for enforcing security policies, but in simple cases it is often easier to "do your grants" on the API. I find manageing the definition of a views more versatile way to implement access control than making (and keeping track of) lots of fine grained GRANTS, which is why I like the second tier of views.

Deviation from abstrattion leads to complication, so apply these heuristics consistently and completely, if at all.

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group