Using Views
While working with SQL, times will often arise when you would like your statements to be re-usable. This is especially the case when working with large or intricate queries. There are few things more frustrating then having to re-type a long query over and over again within psql. Furthermore, it can be highly inefficient to pass excessively large queries over a network to your PostgreSQL server for commonly executed routines.
This is where views can come in handy. Views can be thought of as stored queries, which allow you to create a database object that functions very similarly to a table, but whose contents are dynamically and directly reflective only of the rows which it is defined to select. Views are quite flexible in practice, in that they may address common, simple queries to a single table, as well as extraordinarily complicated ones which may span across several tables.
Creating a View
The following is the syntax for creating a view:
CREATE VIEW view AS query
viewThe name (identifier) of the view that you wish to create.
queryThe complete SQL
SELECTquery that defines the content of the view.
Imagine that you have a table called shipments that relates a unique
shipping identifier with a customer identifier, a book ISBN, and a timestamp reflecting when
the book was shipped. This table is shown in Table 4-1.
Table 4-1. The shipments table
|
Column |
Type |
Modifier |
|---|---|---|
|
|
|
|
|
|
| |
|
|
| |
|
|
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access