Differences between CTE and View

Differences between CTE and View


CTE stands for Common Table expressions can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. A CTE is like a derived table in that it is not stored as an object and lasts only for the duration of the query. Unlike a derived table, a CTE can be self-referencing and can be referenced multiple times in the same query. CTE improves readability and ease in maintenance of complex queries and sub-queries.
A CTE can be used to:

1.            Create a recursive query. For more information, see Recursive Queries Using Common Table Expressions.

2.            Substitute for a view when the general use of a view is not required; that is, you do not have to store the definition in metadata.

3.            Enable grouping by a column that is derived from a scalar sub select, or a function that is either not deterministic or has external access.

Syntax structure for a CTE:

WITH expression_name [ ( column_name [,...n] ) ]

( CTE_query_definition )

The list of column names is optional only if distinct names for all resulting columns are supplied in the query definition.
The statement to run the CTE is:

SELECT <column_list>
FROM expression_name;

A view is a virtual table which doesn’t physically store any data, it consists of columns from one or more tables. So, whenever we query a view then it retrieves data from the underlying base tables. It is a query stored as an object. Views are used for security purpose in databases, views restrict the user from viewing certain column and rows means by using view we can apply the restriction on accessing the rows and columns for specific user. Views display only those data which are mentioned in the query, so it shows only data which is returned by the query that is defined at the time of creation of the View.

Syntax structure for a View:
CREATE VIEW view_name AS

  SELECT columns
  FROM tables

  [WHERE conditions];
Advantages of CTE over View are:

Common Table Expressions offer the same functionality as a view, but are ideal for one-off usages where you don't necessarily need a view defined for the system. Even when a CTE is not necessarily needed, it can improve readability.
Using a CTE offers the advantages of improved readability and ease in maintenance of complex queries. The query can be divided into separate, simple, logical building blocks. These simple blocks can then be used to build more complex, interim CTEs until the result set is generated.

Next: Differences between Temp Table and Table Variable