Lesson 12 of 15 · 20 min

Views

By the end of this lesson you can create a view, query it, explain why it always shows current data, and replace or recreate it when its columns change.

A view is a saved query with a name. Once created, you can SELECT from it exactly as if it were a table, join it to other tables, filter it and aggregate it. The difference is what is stored: a table stores rows; a view stores only the query. Every time you read from a view, PostgreSQL runs its query against the current tables and hands you the result.

That has two consequences you should keep in mind:

  • A view is always up to date. Change a product's price and every view that uses the price shows the new value immediately, with no refresh step.
  • A view is not faster than the query inside it. PostgreSQL substitutes the view's query into yours and plans the whole thing together (which is usually just as efficient as writing the join by hand).
Included with a Formula Quest membership

This lesson, its 4 graded exercises and every other Members lesson in SQL Quest come with a Formula Quest membership that includes SQL (Single Quest with SQL selected, Quest Trio including SQL, or Quest Unlimited), or with SQL access from your organization.

Free to everyone: all of SQL Foundations and Retrieving and Filtering Data, the first lesson of every track, the playground, the dataset library and the SQL reference. See free lessons