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

CustomerIDCustomerNameCountryOrdersRevenue
2Blue Harbor FoodsUK1412
3Cedar & CoCanada1320.75
1Aarav TradersIndia2301.75
7Golden SpoonSingapore1198.4
5Evergreen GrocersUSA1150
4Delta MartIndia2116.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.