Careeroza
CREATE VIEW
SQL Views
A view is a virtual table based on the result of a SELECT. It stores the query, not the data: every time you read the view, the query runs against the current data.
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;Example
Example
A view of order totals per customer, then queried like a table:
CREATE VIEW CustomerSales AS
SELECT c.CustomerID, c.CustomerName, c.Country,
COUNT(o.OrderID) AS Orders, COALESCE(SUM(o.Amount), 0) AS Revenue
FROM Customers c
LEFT JOIN Orders o ON o.CustomerID = c.CustomerID
GROUP BY c.CustomerID, c.CustomerName, c.Country;
SELECT * FROM CustomerSales WHERE Revenue > 0 ORDER BY Revenue DESC;Result: 6 rows
| CustomerID | CustomerName | Country | Orders | Revenue |
|---|---|---|---|---|
| 2 | Blue Harbor Foods | UK | 1 | 412 |
| 3 | Cedar & Co | Canada | 1 | 320.75 |
| 1 | Aarav Traders | India | 2 | 301.75 |
| 7 | Golden Spoon | Singapore | 1 | 198.4 |
| 5 | Evergreen Grocers | USA | 1 | 150 |
| 4 | Delta Mart | India | 2 | 116.9 |
Why Use Views?
- Simplicity: hide a complex join behind a simple name.
- Security: give users access to the view but not the underlying tables (e.g. hide the Salary column).
- Consistency: everyone uses the same definition of "revenue".
- Stability: tables can be restructured while the view keeps the old shape for existing reports.