Search code examples
sqlcommon-table-expressionamazon-athenaprestowith-statement

Syntactical use of WITH in SQL for CTEs and Properties


I know two uses of WITH in SQL:

  1. To signify a CTE (Common Table Expression) clause, creating a temporary table for use in the present query, and
  2. To dictate properties in a CTAS (CREATE TABLE AS) statement, e.g. Presto, AWS Athena, Cloudera, etc.

However, in reading long queries, I have on several occasions had diffculty immediately telling these two uses apart, and I always thought to myself if it would have made more sense to use another word for one of the two, to improve readability and avoid ambiguity.

So my question is: are these two uses related somehow? Do they stem from some common root?


Solution

  • They are not related at all. WITH is a syntactic construct similar to a subquery. The other is used for other purposes.

    An analogy by might the BY in GROUP BY and ORDER BY. Or the AND used for BETWEEN and as a stand-alone boolean operator. They just happen to have the same name.