VIEW

A view is a virtual table defined by an SQL query. By creating a view, you can query the view just like querying a regular table. When a user queries a view, the query result will only include the data from the tables and fields specified in the query that defines the view.

Advantages of Views

  1. Simplify complex SQL queries: By defining complex queries as views, you can directly query the view when needed without rewriting the complex query each time.
  2. Protect data: Views can restrict user access to the data in the underlying tables, allowing them to access only the data defined in the view.
  3. Better data organization: Views can help you better organize and manage data, making it easier to understand and use.

Limitations of Views

  1. Views are read-only and cannot perform DML (insert, update, delete) operations on the view.
  2. The performance of views may be affected by the data volume of the underlying tables and the complexity of the query.

View Management

Use Cases

  1. Calculate profit and post-tax income:
    CREATE VIEW v_sales AS
    SELECT revenue - cost AS profit, (revenue - cost) * tax_rate AS tax_amount, (revenue - cost) * (1 - tax_rate) AS net_income
    FROM table1;
2. Filter employee information for specific departments:
CREATE VIEW v_sales_department AS
SELECT id, name, position, salary
FROM employees
WHERE department = 'Sales';
  1. Summarize the sales data for each month:
    CREATE VIEW v_monthly_sales AS
    SELECT DATE_TRUNC('month', sale_date) AS month, SUM(revenue) AS total_sales
    FROM sales_data
    GROUP BY month;