A Common Table Expression (CTE) is a temporary result set derived from a SELECT statement, and can be used in a SELECT, INSERT, UPDATE, or DELETE statement. CTEs are used to simplify complex queries by breaking them down into smaller, more manageable pieces.

The purpose of CTEs is to make queries easier to read, write and maintain. CTEs can be thought of as named subqueries or temporary views that are only visible within the scope of a single SELECT, INSERT, UPDATE, or DELETE statement. They are not stored as objects in the database and do not impact database performance.

CTEs are particularly useful when dealing with complex queries that involve multiple levels of data aggregation or calculations, or when the same subquery is used in multiple places in a larger query. Using a CTE allows you to write the subquery once and reuse it throughout the query, making the overall structure of the query simpler and easier to understand.

In terms of when to use CTEs, they are a good choice when you want to:

Break down a complex query into smaller, more manageable pieces.
Improve query readability and maintainability by giving meaningful names to intermediate results.
Reuse intermediate results within the same query.
Simplify complex calculations or aggregations by breaking them down into multiple steps.
In general, if you have a query that is becoming difficult to understand or maintain due to its complexity, a CTE may be a good solution to simplify the query and make it easier to work with.
spam fails_task lang_mismatch pii not_appropriate hate_speech sexual_content quality toxicity humor helpfulness creativity violence