AI Hints
Home›PostgreSQL Tutorial›Views and Schemas
PostgreSQL · Lesson 70 of 120

Views

Saved queries.

⏱ 2 min read▶ Video at 1:03:09🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

The team runs the same revenue by genre query every day. A view saves a query under a name. Then it can be used just like a table.

  • Same query daily
  • Save it
  • Use like a table

A revenue view

Create view saves the query as genre revenue. Then we select from it like a table, and even filter it. Run it. The top three genres by revenue.

query.sqlsql
CREATE VIEW genre_revenue AS
SELECT b.genre, sum(i.quantity * b.price) AS revenue
FROM order_items i JOIN books b USING (book_id)
GROUP BY b.genre;

SELECT * FROM genre_revenue
ORDER BY revenue DESC
LIMIT 3;
Output
CREATE VIEW
   genre    | revenue
------------+---------
 Technology | 9576.04
 Fantasy    | 7927.05
 Mystery    | 7440.86
(3 rows)

Why views

Views hide complex joins behind a simple name. They give everyone the same definition of a number, like revenue. They can limit which columns people see. And they store no data, so they're always up to date.

keyvalue
Simplifyhide joins
Consistencyone definition
Securitylimit columns
Datanone stored, always fresh

Summary

Views save queries under a name, and always show fresh data. Next, materialized views, which save the results too.

Key takeaways
  • CREATE VIEW
  • Like a table
  • Always fresh
Next up: Materialized Views — save the results