WITH clause used to introduce a Common Table Expression (CTE).
CTEs are supported in most modern SQL engines and can be useful
in performance tuning. In Esqueleto, CTEs should be used as a
subquery memoization tactic. When writing plain SQL, CTEs
are sometimes used to organize the SQL code, in Esqueleto, this
is better achieved through function that return SqlQuery values.
select $ do
cte <- with subQuery
cteResult <- from cte
where_ $ cteResult ...
pure cteResult
WARNING: In some SQL engines using a CTE can diminish performance. In these engines the CTE is treated as an optimization fence. You should always verify that using a CTE will in fact improve your performance over a regular subquery.
Notably, in PostgreSQL prior to version 12, CTEs are always fully
calculated, which can potentially significantly pessimize queries. As of
PostgreSQL 12, non-recursive and side-effect-free queries may be inlined and
optimized accordingly if not declared MATERIALIZED to get the previous
behaviour. See the PostgreSQL CTE documentation,
section Materialization, for more information. To use a MATERIALIZED query
in Esquelto, see functions withMaterialized and withRecursiveMaterialized.
Since: 3.4.0.0