✅ Common Table Expressions in SQL 👇

What is a common table expression (CTE)?

CTEs are short lived.

CTEs are virtual tables which are created during the execution of a query, used by the query, and eliminated after query execution.

Syntax of CTE

Syntax of a CTE. Image by Author.

CTE can be can referenced within a SELECT, INSERT, UPDATE, or DELETE statement.

Two types of CTE

An example of a non-recursive CTE.

In MySQL and PostgreSQL, the RECURSIVE keyword is required.

An example to Recursive CTE to generate the numbers from 1 to 5.

When to Use CTEs

Error Message - "Cannot perform an aggregate function on an expression containing an aggregate or a subquery."

CTE vs. Sub-queries

Multiple References of a CTE. Image by Author.
Readability with a CTE in Multiple Tables Scenario. Image by Author.

In fact, in the next 3-months, I will be adding 15+ new articles covering multiple use-cases from data analytics and ML/AI. 🍾 🙌 🎉

--

--

Business of data and AI. ➤ https://bit.ly/3tZE50E

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store