Views
Give a query a name with CREATE VIEW, see why it stores no rows, and learn when you can write through a view and how CHECK OPTION guards it.
A named query
A view gives a name to a query. After CREATE VIEW high_scorers AS SELECT ... WHERE points >= 30, you can write SELECT * FROM high_scorers and use the view almost anywhere you could use a table.
A view stores no rows. The manual says it is not physically materialized: the query runs again every time the view is used. So a view always shows the current data.
One definition, many users
A long join or a filter that many reports need can be written once and given a name. The manual calls liberal use of views a key aspect of good SQL design, because they hide the details of how the tables are built behind a stable interface. If the tables change, you update the view, and the code that reads it keeps working.
A view follows its tables
CREATE VIEW high_scorers AS
SELECT id, name, team, points
FROM players
WHERE points >= 30;The view shows Asha (31) and Gus (40). Update Gus to 10 points in the players table, and the view now shows only Asha. You changed the table, not the view, and it kept up because it is just a query.
A simple view, with one table in FROM and no DISTINCT, GROUP BY, aggregates or set operations, is automatically updatable: you can INSERT, UPDATE and DELETE through it, and the change goes to the base table.
Change the table, change the view
Read the view, then drop Gus to 10 points. Insert Zed with 10 points, with and without WITH CHECK OPTION. Then try the team_sizes view.
| idinteger | nametext | teamtext | pointsinteger |
|---|---|---|---|
| 1 | Asha | Red | 31 |
| 7 | Gus | Green | 40 |
| nametext | teamtext | pointsinteger |
|---|---|---|
| Asha | Red | 31 |
| Ben | Blue | 17 |
| Chen | Red | NULL |
| Dara | Green | 24 |
| Eli | Blue | NULL |
| Fay | Red | 24 |
| Gus | Green | 40 |
| Hana | Blue | 17 |
The CREATE VIEW text at the top is saved once. Pick a statement and press Run statement, then watch the view and the base table.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A view is a named query. It stores no rows and always shows the current data.
- A simple view over one table is automatically updatable, and writes go to the base table.
- Without WITH CHECK OPTION a view can accept rows it cannot show. With it, the insert is refused.
- A view with GROUP BY, DISTINCT, aggregates or set operations is read-only. A materialized view is a different thing that stores its result.
Done with this concept?
Mark it complete to track your progress. No login needed.