Question

Can anybody in here tell me the difference of VIEW and WITH, as I have searched many placed and I can't find anything about it.
My thoughts is that VIEW and WITH are the same, except for VIEWs is saved as a Schema-object, but I can be wrong

Was it helpful?

Solution

SQL views and with clauses are very similar. Here are some differences.

Views create an actual object in the database, with associated metadata and security capabilities. With statements are only part if a single query.

In many databases, views have options, for instance to index them or to "instantiate" them.

With statements offer the opportunity to have recursive CTEs, in some databases. This is not possible for views.

For simple subqueries incorporated into queries, they are quite similar. The choice really depends on whether you want to create a reusable code (views) or are focused on a single query (with).

OTHER TIPS

Fundamentally, the definition of a view is saved in the database and can be reused by any query, whereas a WITH clause (or Common Table Expression, or CTE) is tied to one specific query and can only be reused by copying.

Otherwise, they will be substantially the same.

If you use a recursive WITH clause, then you can't achieve the same result in a VIEW unless the view definition itself uses a WITH clause (which is legitimate).

In a few words, WITH is a clause that is used in DML, VIEW is a database object. View definition may contain query that uses WITH. You can consider WITH as a variation of derived table (in Microsoft terminology) or inline view(in Oracle) that is defined before main DML and has an ability to refer to itself (recursive queries)

WITH is also used in SQLServer in a different context(query hints).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top