8. Common Table Expressions
PostgreSQL CTE
(Introduce us to PostgreSQL common table expressions or CTEs)
A CTE is a temporary result set which you can reference within another SQL statement including
SELECT, INSERT, UPDATE or DELETE
They only exist during execution of the query
Its syntax is
In its syntax,
First, specify the name of the CTE following by an optional column list
Second, inside the body of the
WITH
clause, specify a query that returns a result set. If you do not specify the column list after CTE name, the select list of theCTE_query_definition
will become the column list of the CTEThird, use the CTE like a table or view in the
statement
which can beSELECT, INSERT, UPDATE or DELETE
CTE are commonly used to simplify complex joins and subqueries in PostgreSQL
Example 1
We will use film
and rental
tables from sample db
Example 2 (Joining a CTE with a table)
We will use rental
and staff
tables
Example 3 (CTE with a window function)
PostgreSQL CTE advantages
Improve the readability of complex queries. You use CTEs to organize complex queries in a more organized and readable manner.
Ability to create recursive queries
Use in conjunction with window functions. You can use CTEs in conjunction with window functions to create an initial result set and use another select statement to further process this result set.
Recursive query using CTEs
(discuss the recursive query and learn how to apply it in various contexts)
A recursive query is a query that refers to a recursive CTE
They are useful in many situations such as querying heirarchical data like organizational structure, bill of materials, etc
This is the syntax of recursive CTE
This syntax has three elements
non-recursive-term: the non-recursive term is a CTE query definition that forms the base result set of the CTE structure
recursive-term: the recursive term is one or more CTE query definitions joined with the non-recursive term using the
UNION
orUNION ALL
operator. The recursive term references the CTE name itselftermination-check: the recursive term references the CTE name itselfg
Example (get all subordinates of the manager with the id 2)
Last updated