SQL Server View is a virtual table derived from one or more tables or other views. It does not store data itself but rather represents a stored SQL query that dynamically retrieves data from its underlying tables whenever the view is queried.
Example
Employees Table:
EmployeeID
FirstName
LastName
DepartmentID
Salary
1
John
Smith
1
50000
2
Jane
Doe
2
60000
3
Michael
Johnson
1
55000
4
Emily
Brown
3
52000
Departments Table:
DepartmentID
DepartmentName
1
HR
2
Finance
3
IT
Now, let's create a view that shows the employees along with their department names:
-- Create a view to show employees with department names
CREATE VIEW EmployeeDetails AS
SELECT e.EmployeeID, e.FirstName, e.LastName, d.DepartmentName, e.Salary
FROM Employees e
JOIN Departments d ON e.DepartmentID = d.DepartmentID;
In this example:
We create a view named EmployeeDetails.
The view selects columns EmployeeID, FirstName,
LastName, DepartmentName, and Salary from the
Employees table (e) and the Departments table (d).
It joins the Employees table with the Departments table based on the
DepartmentID column to retrieve the department name for each employee.
The EmployeeDetails view now provides a consolidated view of employee details along with their department names.
After creating the view, you can query it just like a regular table:
-- Query the EmployeeDetails view
SELECT *
FROM EmployeeDetails;
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
SQL Server View is a virtual table derived from one or more tables or other views. It does not store data itself but rather represents a stored SQL query that dynamically retrieves data from its underlying tables whenever the view is queried.
Example
Employees Table:
Departments Table:
Now, let's create a view that shows the employees along with their department names:
In this example:
EmployeeDetails.EmployeeID,FirstName,LastName,DepartmentName, andSalaryfrom theEmployeestable (e) and theDepartmentstable (d).Employeestable with theDepartmentstable based on theDepartmentIDcolumn to retrieve the department name for each employee.EmployeeDetailsview now provides a consolidated view of employee details along with their department names.After creating the view, you can query it just like a regular table:
Read more
Why do you use SQL Command and Queries in SQL Server?
What is SQL Database and why is it so popular?
Write a query to retrieve the total number of employees in each department.