×

sql · level 3 · unit 4 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is a saved query you can read like a table.

Some questions get asked every day. Save the query with and the database remembers it. From then on, SELECT * FROM name runs it for you. Unlike a CTE, a view lasts beyond one statement.

A view stores the query, not the rows. Every time you read it, it runs again on the latest data, so it is never out of date.

Views give a whole team one agreed answer, such as one way of adding up spending. DROP VIEW name removes one.

CREATE VIEW customer_spend AS
SELECT c.name, COUNT(o.id) AS orders, COALESCE(SUM(o.total), 0) AS spent
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id;

SELECT name, spent FROM customer_spend ORDER BY spent DESC, name;

Put ORDER BY in the query that reads the view, not inside the view itself.