Lessons › SQL › Deep Dive: Database Admin & ETL
SQL lesson
Views
A view is a saved query given a name so you can treat it like a table - reference it anytime without rewriting the underlying logic.
Try this lesson free →Example
Saving Retail Reporting Logic with SQL Views
CREATE VIEW completed_orders AS
SELECT order_id, customer_id, revenue, discount, order_date
FROM orders
WHERE status = 'completed';
SELECT customer_id, SUM(revenue) AS total_revenue
FROM completed_orders
GROUP BY customer_id
ORDER BY total_revenue DESC| customer_id | total_revenue |
|---|---|
| C101 | 531.25 |
| C102 | 89.99 |
Step by step
- CREATE VIEW saves a query so you can reuse it like a table.
CREATE VIEW completed_orders AS - After SELECT, list the column names you want, separated by commas.
CREATE VIEW completed_orders AS SELECT order_id, customer_id, revenue, discount, order_date - FROM tells SQL which table to pull the data from.
CREATE VIEW completed_orders AS SELECT order_id, customer_id, revenue, discount, order_date FROM orders
Practice
1. Write a CREATE VIEW statement called orders_summary that selects all rows from orders grouped by customer_id.
CREATE VIEW orders_summary AS SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id2. Write a CREATE VIEW statement called store_sales_summary that selects all rows from store_sales grouped by store_id.
CREATE VIEW store_sales_summary AS SELECT store_id, COUNT(*) FROM store_sales GROUP BY store_id3. Write a CREATE VIEW statement called products_summary that selects all rows from products grouped by product_id.
CREATE VIEW products_summary AS SELECT product_id, COUNT(*) FROM products GROUP BY product_id4. Write a CREATE VIEW statement called customers_summary that selects all rows from customers grouped by email.
CREATE VIEW customers_summary AS SELECT email, COUNT(*) FROM customers GROUP BY email5. Write a CREATE VIEW statement called returns_summary that selects all rows from returns grouped by return_id.
CREATE VIEW returns_summary AS SELECT return_id, COUNT(*) FROM returns GROUP BY return_idLearn 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 →