VIEW

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

Creating a View

CREATE VIEW [IF NOT EXISTS] [schema_name.]<view_name> [ (column_list) ] [ COMMENT 'comment' ] AS <query>;

Parameter Description

ParameterDescription
IF NOT EXISTSOptional. If the view already exists, skip without raising an error
schema_nameOptional. Specifies the schema to which the view belongs
view_nameThe name of the view
column_listOptional. Specifies the column names of the view; the number must match the number of columns in the query result
COMMENTOptional. Adds a comment to the view
queryThe SELECT query that defines the view

Examples

-- Create a basic view CREATE VIEW v_sales AS SELECT revenue - cost AS profit, (revenue - cost) * tax_rate AS tax_amount FROM sales_table; -- Create a view with a comment CREATE VIEW v_sales_department COMMENT 'Sales department employee view' AS SELECT id, name, position, salary FROM employees WHERE department = 'Sales'; -- Create an aggregation view 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;

Advantages of Views

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

Limitations of Views

  1. Views are read-only; DML operations (INSERT, UPDATE, DELETE) cannot be performed on views.
  2. View performance may be affected by the data volume of the underlying tables and the complexity of the query.
  3. Views do not store data; the underlying query is re-executed each time the view is queried.
  4. Views do not support Time Travel queries.

View Management

Differences Between Views and Materialized Views

DimensionViewMaterialized View
Data StorageDoes not store dataStores pre-computed results
Query PerformanceRe-calculated on each queryReads pre-stored results directly for better performance
Data FreshnessReal-timeDepends on refresh frequency
Storage CostNoneOccupies storage space
Use CasesSimple queries, logical abstractionComplex aggregations, frequent queries