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 →Example
Save a query under a name
CREATE VIEW category_view AS
SELECT category, SUM(revenue) AS total
FROM orders
GROUP BY category| category | total |
|---|---|
| Electronics | 598.99 |
| Clothing | 299.00 |
Step by step
- The view's name, then AS.
CREATE VIEW category_view AS SELECT category, SUM(revenue) AS total FROM orders GROUP BY category - 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 - 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
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 category2. Make a view called big_orders that shows only the orders over 100.
CREATE VIEW big_orders AS SELECT * FROM orders WHERE revenue > 1003. 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_id5. 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 →