Views
Swipe to show menu
Views in SQL are virtual tables that are defined by a query. Instead of storing data themselves, views present data from one or more tables in a specific format, making it easier to work with complex queries or to expose only certain parts of the data to users. You can create a view using the CREATE VIEW statement, and then query it just like a regular table.
Suppose you have two tables: employees and sales. You might want to frequently see each employee's name along with the total sales they have made. Rather than writing a complex join and aggregation every time, you can define a view that does this for you. Once the view is created, you simply select from it as needed.
1234567891011121314151617-- Drop the view if it already exists to ensure a fresh creation DROP VIEW IF EXISTS employee_total_sales; -- Create a view that shows each employee's name and their total sales CREATE VIEW employee_total_sales AS SELECT e.name AS employee_name, SUM(s.amount) AS total_sales FROM employees e LEFT JOIN sales s ON e.employee_id = s.employee_id GROUP BY e.name; -- Query the view to see the results SELECT * FROM employee_total_sales;
Views are useful in several scenarios. When you have a complex query that you need to use repeatedly, a view lets you save it and refer to it as if it were a table, making your SQL code easier to read and maintain. Views also provide abstraction: users can access only the columns and rows exposed by the view, without needing to know the underlying table structures or relationships. This abstraction is especially valuable for security, as you can restrict users' access to sensitive data by giving them permission to access only certain views rather than the base tables themselves.
1. What is a view in SQL?
2. Can you update data through a view?
3. How do views enhance security?
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat