Sobes.tech
Junior

What is a view in the context of databases and what is it used for?

sobes.tech AI

Answer from AI

A view is a virtual table based on the result of an SQL query. It does not store data physically but represents a saved query whose result can be used as a regular table.

Used for:

  • Simplifying complex queries: Hides the complexity of join or subquery queries, providing a simpler interface.
  • Access restrictions: Allows showing only certain columns or rows from the base table to the user, ensuring security.
  • Providing alternative data views: Enables viewing data from different tables in a convenient format.
  • Ensuring compatibility: Can be used to create a new data view without changing the existing database structure.

Example of creating a view:

CREATE VIEW CurrentEmployees AS
SELECT EmployeeID, FirstName, LastName, DepartmentName
FROM Employees e
JOIN Departments d ON e.DepartmentID = d.DepartmentID
WHERE e.IsActive = TRUE;

Using the view:

SELECT * FROM CurrentEmployees WHERE DepartmentName = 'IT';