Views: named queries
When a complex query is used again and again, copying and pasting it is a bad idea: if it has to be fixed, it must be fixed everywhere. A view (VIEW) is a query stored in the database with a name; afterwards you use it as if it were a table. The view does not store data of its own: each time you query it, the engine runs the defining query on the real tables, so it always sees current information.
CREATE VIEW order_totals AS
SELECT o.order_id,
o.customer_id,
o.order_date,
o.status,
SUM(oi.quantity * oi.unit_price) AS order_total
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.order_id, o.customer_id, o.order_date, o.status;
-- Now the view is used like any table
SELECT * FROM order_totals WHERE order_total > 500 ORDER BY order_total DESC;
SELECT status, COUNT(*) AS orders, SUM(order_total) AS amount
FROM order_totals
GROUP BY status;With order_totals, questions that used to require a JOIN and an aggregation are solved with a simple SELECT. Views offer three advantages. Reuse: the logic is in one place. Simplicity: whoever queries does not need to know the details of the tables. Security: you can give access to a view that shows only some columns or rows (for example without emails) and not to the original tables with GRANT SELECT ON view TO user.
Changing and dropping views
CREATE OR REPLACE VIEW replaces the definition, provided the existing columns keep their name and type; if you want to change that, you must DROP VIEW and create it again. A view can be built on other views, but it is better not to chain too many layers because it becomes hard to debug and to optimize. Simple views (one table, no aggregations) can even be updated with INSERT, UPDATE and DELETE in PostgreSQL; complex ones cannot.
-- One row per customer, including those with no orders
CREATE OR REPLACE VIEW customer_summary AS
SELECT c.customer_id,
c.name,
c.city,
COUNT(ot.order_id) AS orders,
COALESCE(SUM(ot.order_total), 0) AS total_spent
FROM customers c
LEFT JOIN order_totals ot
ON ot.customer_id = c.customer_id AND ot.status <> 'cancelled'
GROUP BY c.customer_id, c.name, c.city;
SELECT * FROM customer_summary ORDER BY total_spent DESC, name;
-- A safe view for a support team: no emails, only delivered orders
CREATE VIEW support_orders AS
SELECT order_id, customer_id, order_date FROM orders WHERE status = 'delivered';
DROP VIEW support_orders;Materialized views
If the view's query is heavy (millions of aggregated rows) and the data does not need to be up to the second, PostgreSQL offers materialized views: they store the result on disk like a table, and are updated when you ask with REFRESH MATERIALIZED VIEW. Reads are instantaneous, at the cost that data may be somewhat stale. You can even create indexes on them. They are very common for reports and dashboards refreshed every night. MySQL does not have them natively; neither does SQLite.
CREATE MATERIALIZED VIEW monthly_sales AS
SELECT DATE_TRUNC('month', order_date)::DATE AS month,
COUNT(*) AS orders,
SUM(order_total) AS revenue
FROM order_totals
WHERE status <> 'cancelled'
GROUP BY 1;
SELECT * FROM monthly_sales ORDER BY month;
-- After new orders arrive, the stored result is stale until:
REFRESH MATERIALIZED VIEW monthly_sales;✎ Meine Notizen
Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen