Back to all posts

What is View in SQL server

A view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. IF OBJECT_ID('ViewTable','…

A view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table.

SQL
IF OBJECT_ID('ViewTable','V') IS NOT NULL
BEGIN
	DROP VIEW ViewTable
END

GO

CREATE VIEW ViewTable AS
(
	SELECT 
		ED.empid,ED.firstname, C.categoryname,
		SUM(OD.unitprice) as UnitPrice, 
		SUM(OD.qty) as Qty, 
		SUM(OD.unitprice)*SUM(OD.qty) as Amount
	FROM . ED 
	INNER JOIN Sales.Orders O ON O.empid = ED.empid
	INNER JOIN Sales.OrderDetails OD ON OD.orderid = O.orderid
	INNER JOIN Production.Products P ON P.productid = OD.productid
	INNER JOIN Production.Categories C ON C.categoryid = P.productid
	GROUP BY ED.empid,ED.firstname, C.categoryname
)
GO
--Modiy View by using Alter
ALTER VIEW ViewTable AS
(
	SELECT 
		ED.empid,ED.firstname, C.categoryname,
		SUM(OD.unitprice) as UnitPrice, 
	--	SUM(OD.qty) as Qty, 
		SUM(OD.unitprice)*SUM(OD.qty) as Amount
	FROM . ED 
	INNER JOIN Sales.Orders O ON O.empid = ED.empid
	INNER JOIN Sales.OrderDetails OD ON OD.orderid = O.orderid
	INNER JOIN Production.Products P ON P.productid = OD.productid
	INNER JOIN Production.Categories C ON C.categoryid = P.productid
	GROUP BY ED.empid,ED.firstname, C.categoryname
)
GO



SELECT * FROM ViewTable A
WHERE UnitPrice>70
Order by UnitPrice DESC

INSERT, UPDATE, or DELETE operations on a view in SQL Server not possible.

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.