BBampaa

Lessons › SQL › Chapter 7: Creating and changing tables

SQL lesson

Views

A view is a saved query with a name. You SELECT from it like a table, but it runs its query again each time, so it always shows the latest data. That's the difference from the last level: CREATE TABLE … AS keeps a copy, and CREATE VIEW stays up to date.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Save a query under a name

CREATE VIEW category_view AS
SELECT category, SUM(revenue) AS total
FROM orders
GROUP BY category

Result:

categorytotal
Electronics598.99
Clothing299.00

Step by step

  1. The view's name, then AS.
    CREATE VIEW category_view AS SELECT category, SUM(revenue) AS total FROM orders GROUP BY category
  2. Saved with the view. It runs again every time you use the view.
    CREATE VIEW category_view AS SELECT category, SUM(revenue) AS total FROM orders GROUP BY category
  3. Always today's numbers, with no query to rewrite.
    CREATE VIEW category_view AS SELECT category, SUM(revenue) AS total FROM orders GROUP BY category

Practice

Try each one in your head first, then open the answer.

1. Make a view called category_view with each category's total revenue from orders. Name the total column total.
CREATE VIEW category_view AS SELECT category, SUM(revenue) AS total FROM orders GROUP BY category
2. Make a view called big_orders that shows only the orders over 100.
CREATE VIEW big_orders AS SELECT * FROM orders WHERE revenue > 100
3. Make a view called clothing_orders that shows only the Clothing orders from orders.
CREATE VIEW clothing_orders AS SELECT * FROM orders WHERE category = 'Clothing'
4. Make a view called customer_totals with each customer's total revenue from orders. Name the total column total.
CREATE VIEW customer_totals AS SELECT customer_id, SUM(revenue) AS total FROM orders GROUP BY customer_id
5. Make a view called march_orders that shows only the orders from March 2024.
CREATE VIEW march_orders AS SELECT * FROM orders WHERE order_date BETWEEN '2024-03-01' AND '2024-03-31'

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed