Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between SQL View and WITH clause

Tags:

sql

sql-view

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

like image 404
The87Boy Avatar asked May 20 '12 15:05

The87Boy


People also ask

Can we use with clause in view?

Common Table Expressions (WITH clause) is not allowed in views or derived tables.

What is difference between WITH clause and subquery?

The main difference between with clause and a subquery in Oracle is that you can reference a query within the clause multiple times. You can then do some optimizations with it like turning it into a temp table using materialize hint. You can also do recursive queries with it by referencing itself inside a with clause.

What is the with clause in SQL?

The WITH clause in SQL was introduced in standard SQL to simplify complex long queries, especially those with JOINs and subqueries. Often interchangeably called CTE or subquery refactoring, a WITH clause defines a temporary data set whose output is available to be referenced in subsequent queries.

What is SQL View with statement?

In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.


2 Answers

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 of 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).

like image 183
Gordon Linoff Avatar answered Sep 25 '22 13:09

Gordon Linoff


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).

like image 31
Jonathan Leffler Avatar answered Sep 22 '22 13:09

Jonathan Leffler