- Simplification: Views simplify complex queries by storing the logic in the view definition. This makes it easier to reuse the same logic without having to write the query repeatedly.
- Security: Views allow you to restrict access to specific columns or rows of a table. You can provide users access to only the data they need without exposing sensitive information.
- Data abstraction: Views help abstract underlying data complexities, providing a more user-friendly or business-specific perspective of the data.
What are views in SQL?
Views in SQL are a simple and powerful feature that makes working with data easier. They allow us to create virtual tables from queries without storing the data.
Suppose you are managing a library. You want a quick way to see all books borrowed this month without searching through every record repeatedly. SQL views can help—acting as personalized windows to your data. They let you save a search query and access its results dynamically without affecting the underlying data.
What is a view in SQL?
A view in SQL is a virtual table that is based on a SELECT query. It does not store any data on its own but retrieves it from one or more existing tables. Views are useful for simplifying complex queries and controlling access to specific data.
For example, if you frequently need to see only the employees from the HR department, instead of writing the same query every time, you can create a view for it.
Syntax of a view
The syntax for creating a view is simple:
CREATE VIEW view_name ASSELECT column1, column2, ...FROM table_nameWHERE condition;
view_name: The name you give to the view.SELECT: The query that defines what the view will display.WHERE: An optional clause to filter data.
Let’s see how this works in practice.
Create views in SQL
Creating a view helps you save time by reusing the same query. You can also hide specific columns from users for security purposes.
Example 1: Create view
-- Step 1: Create the database CompanyCREATE DATABASE Company;use Company;-- Step 2: Create the Employees tableCREATE TABLE Employees (EmployeeID INT PRIMARY KEY,Name VARCHAR(50),Department VARCHAR(50),Salary DECIMAL(10, 2));-- Step 3: Insert sample data into the Employees tableINSERT INTO Employees (EmployeeID, Name, Department, Salary)VALUES(1, 'Alice', 'HR', 60000),(2, 'Bob', 'Finance', 75000),(3, 'Charlie', 'HR', 58000),(4, 'Diana', 'IT', 72000);-- Step 4: Create a view to display only HR employeesCREATE VIEW EmployeeView ASSELECT EmployeeID, Name, DepartmentFROM EmployeesWHERE Department = 'HR';-- Step 5: Query the view to display the dataSELECT * FROM EmployeeView;
This creates a view EmployeeView that shows only the employees working in the HR department.
Try experimenting by modifying the WHERE clause to view employees from another department (e.g., WHERE Department = 'IT').
Example 2: Calculations in a view
-- The SalaryView includes a bonus calculation which is 10% of the base salary for each employee.CREATE VIEW SalaryView ASSELECT EmployeeID, -- Displaying the unique identifier for each employeeName, -- Displaying the employee's nameBaseSalary, -- Displaying the employee's base salaryBaseSalary * 0.1 AS Bonus -- Calculating the bonus as 10% of the BaseSalary and displaying it as 'Bonus'FROM Employees; -- Fetching data from the 'Employees' table
This adds a calculated column Bonus to the SalaryView, showing 10% of the base salary for each employee.
View update in SQL
Sometimes, you might need to change the definition of a view. Instead of deleting and recreating it, you can use the CREATE OR REPLACE VIEW statement.
Example: Update view
-- The EmployeeView now includes an additional column for the JoinDate and filters employees from the 'HR' department.CREATE OR REPLACE VIEW EmployeeView ASSELECT EmployeeID, -- Displaying the unique identifier for each employeeName, -- Displaying the employee's nameDepartment, -- Displaying the department where the employee worksJoinDate -- Displaying the employee's join dateFROM Employees -- Fetching data from the 'Employees' tableWHERE Department = 'HR'; -- Filtering to show only employees from the HR department
This updates EmployeeView to include a new column, JoinDate.
Drop views in SQL
If you no longer need a view, you can delete it using the DROP VIEW statement.
Syntax
DROP VIEW view_name;
Example: Drop view
-- Step 3: Drop the 'EmployeeView' from the database-- This command deletes the existing view named 'EmployeeView'.-- Be cautious when using DROP, as it permanently removes the view, and you will need to recreate it if necessary.DROP VIEW EmployeeView;
This deletes the EmployeeView from the database.
Pros and cons of views
Pros of views | Cons of views |
Makes frequently used or complex queries easier to manage. | Complex views can slow down query performance. |
Exposes only specific columns or rows to users. | Most views are read-only and cannot directly modify data. |
Allows multiple users or applications to use the same logic without rewriting it. | Changing the base table structure may require view adjustments. |
Uses of a view
Views are highly useful in many situations:
Simplify data access: Combine data from multiple tables for easier use.
Secure data: Limit user access to sensitive or unnecessary columns.
Data aggregation: Summarize data for reports, such as totals and averages.
Reusable logic: Define complex queries once and reuse them across applications.
Key takeaways
A view is a virtual table created from a SQL query.
Use
CREATE VIEWto define views andDROP VIEWto remove them.Views are great for simplifying data access and improving security, but they can have performance trade-offs.
Understanding views is an important step in learning SQL and managing databases efficiently.
Ready to learn SQL and become a database expert? Join our Learn SQL course and follow the path to becoming a Database Professional with SQL! Unlock your potential and gain the skills employers seek. Start your journey today!
Frequently asked questions
Haven’t found what you were looking for? Contact Us