

The with clause was introduced with SQL:1999 as a set of optional features. Use CasesĪssign names to columns without a known name I make my living from SQL training, SQL tuning and consulting and my book “SQL Performance Explained”. Read more about this in “ with Clause: Performance Impacts”. “materialize”) its result to prevent double execution. If a with query is referred to multiple times, some databases cache (i.e. The PostgreSQL database was different until version 12: it optimized each with query and the main statement independent of each other. Most databases process with-queries in the same way that they process views: they replace the reference to the query by its definition and optimize the overall query. Query names defined using with mask existing tables or views with the same name.

Each of these queries can refer to the query names previously defined within the same with clause 4 (an often neglected rule-see Compatibility): WITH query_name1 AS ( This query (and subqueries it contains) can refer to the just defined query name in their from clause.Ī single with clause can introduce multiple query names by separating them with a comma (the with keyword is not repeated). With is not a stand alone command like create view is: it must be followed by select. The keyword as finally introduces the definition itself (the query)-again in parentheses. The syntax after the keyword with is the same as it is for create view: it starts with the query name, and optionally 3 and in parenthesis the name of the columns it returns. The with clause is, simply put, an optional prefix for select: 2 WITH query_name (column_name1. Note that the recursive from of the with clause is covered in another article.

The with clause is also known as common table expression (CTE) and subquery factoring. This makes it possible to improve the structure of a statement without polluting the global namespace. They are not stored in the database schema: instead, they are only valid in the query they belong to. SQL:1999 added the with clause to define “statement scoped views”. Once created, a view has a name in the database schema so that other queries can use it like a table. To make queries reusable, SQL-92 introduced views. 0 The building block of SQL are queries 1-not instructions. In SQL, neither functions nor procedures are first-class citizens in the same way that subqueries are. This makes the code reusable and improves readability.Įven though SQL has functions and procedures as well, they are not the right tools for building easily understandable and reusable units. In software engineering, it is common practice to group instructions as small and easily comprehensible units-namely functions or methods.
