Any query that you can write using only subqueries in the FROM
clause and regular joins can use CTEs with direct substitution.
Subqueries are needed for:
- Correlated subqueries (which are generally not in the
FROM
clause).
- Lateral joins (in databases that support
LATERAL
or APPLY
keywords in the FROM
clause).
- Scalar subqueries.
Sometimes, a query could be rewritten to avoid these constructs.
Subqueries in the FROM
clause (except for lateral joins) can be written using CTEs.
Why are subqueries used and not CTEs? The most important reason is that CTEs are a later addition to the SQL language. With the exception of recursive CTEs, they are not really needed. They are really handy when a subquery is being referenced more than one time, but one could argue that a view serves the same purpose.
As mentioned in the comments, CTEs and subqueries might be optimized differently. This could be a performance gain or loss, depending on the query and the underlying indexes and so on.
WITH
could not be nested in some dialects where subquery can. But in general CTEs are easier to maintain and read.