PostgreSQL – Common Table Expression (CTE)
Last Updated :
08 Nov, 2024
In PostgreSQL, Common Table Expressions (CTEs) are a powerful feature that allows us to define temporary result sets that can be referenced within other SQL statements. This includes statements like SELECT, INSERT, UPDATE, or DELETE. CTEs make complex queries more readable and maintainable by breaking them into modular, reusable subqueries.
The use of CTEs in PostgreSQL simplifies working with recursive queries and complex joins, thus improving performance and query organization. This article explains how to use Common Table Expressions (CTEs) in PostgreSQL, complete with syntax, examples, and best practices.
PostgreSQL – Common Table Expression (CTE)
A CTE (Common Table Expression) is a temporary result set that we can define within the execution scope of a query. Defined using the WITH
clause, a CTE can be referenced multiple times in a SQL statement, improving query performance and readability.
It’s particularly useful for simplifying complex queries, especially those involving multiple subqueries. In PostgreSQL, CTEs can also be recursive, making them an excellent choice for hierarchical or tree-like data structures, such as organizational charts or file systems.
Syntax
WITH cte_name (column_list) AS (
CTE_query_definition
)
statement;
Key Terms
- CTE Name: The first step is to set the name of the CTE, followed by an optional column list.
- CTE Query Definition: Specify a query that returns the result set within the body of the
WITH
clause. If the column list is not specified, the select list of the CTE_query_definition
will become the column list of the CTE.
- Usage: Finally, use the CTE like a table or view in the statement, which can be a
SELECT
, INSERT
, UPDATE
, or DELETE
.
Examples of PostgreSQL CTE
For examples below, we will be using the sample database (ie, dvdrental). Let’s explore some real-world PostgreSQL CTE examples to understand their functionality and use cases
Example 1: Categorizing Films by Length
In this example, we will define a CTE named cte_film
using the WITH
clause with the film
table. We will categorize films based on their length as ‘Short‘, ‘Medium‘, or ‘Long’.
Query:
WITH cte_film AS (
SELECT
film_id,
title,
(CASE
WHEN length < 30 THEN 'Short'
WHEN length < 90 THEN 'Medium'
ELSE 'Long'
END) length
FROM
film
)
SELECT
film_id,
title,
length
FROM
cte_film
WHERE
length = 'Long'
ORDER BY
title;
Output

Explanation:
In this query, the CTE cte_film
first categorizes films based on their length. The main SELECT
query then filters these films to only show those categorized as ‘Long’. This makes the query simpler and more readable.
Example 2: Ranking Films by Length Using the RANK() Function
In this example, we will use the CTE with the RANK()
window function in the film
table to rank the films based on their length. The films will be ranked within each rating category.
Query:
WITH cte_film AS (
SELECT film_id,
title,
rating,
length,
RANK() OVER (
PARTITION BY rating
ORDER BY length DESC)
length_rank
FROM
film
)
SELECT *
FROM cte_film
WHERE length_rank = 1;
Output

Explanation:
In this query, the CTE cte_film
calculates the rank of each film within its rating category based on its length. The RANK()
window function ranks films in descending order of their length. The main query then selects only the highest-ranked films (length_rank = 1
)
Important Points About PostgreSQL Common Table Expressions (CTEs)
- CTEs are used to define temporary result sets that exist only during the execution of a query.
- The
WITH
keyword is used to define a CTE, followed by the CTE name and an optional column list.
- CTEs can be used with
SELECT
, INSERT
, UPDATE
, and DELETE
statements.
- PostgreSQL supports recursive CTEs, which are useful for working with hierarchical data, such as organizational structures or tree models.
Conclusion
Common Table Expressions (CTEs) are a powerful feature in PostgreSQL that enable us to simplify complex queries, improve readability, and enhance SQL code maintainability. Whether we’re using CTEs for recursive queries, window functions, or simplifying joins, they are an essential tool in any PostgreSQL developer’s toolkit.
Similar Reads
SQL Server Common Table Expressions
SQL Server is a relational database management system (RDBMS) that is used to handle complex data and maintain it in of tabular manner. With the help of SQL Server, one can easily protect their data as it provides various security features. In this article, we are going to explore SQL server's CTE a
8 min read
PL/SQL Common Table Expressions
PL/SQL Common Table Expressions (CTEs) make complex queries easier to write and understand by creating temporary result sets. We can use it multiple times in the same query. They help organize and simplify your code, especially for handling hierarchical data or recursive relationships. CTEs make you
10 min read
MySQL Common Table Expressions
One of the most powerful features added in MySQL version 8.0 is common table expressions, which allow for the construction of temporary result sets within a single SQL query. In our daily life queries, we often use common table expressions and it makes our work easier. In this article, we will under
6 min read
PostgreSQL - Comparing Tables
Comparing tables in PostgreSQL is a common task when you need to identify differences between datasets. This can be especially useful when you are merging tables, validating data, or performing quality checks. In this article, we'll explore two of the most commonly used techniques for comparing tabl
3 min read
PostgreSQL - CREATE TABLE
In PostgreSQL, the CREATE TABLE statement is used to define a new table within a database. It allows us to specify the table's structure, including column names, data types, and constraints, ensuring data integrity and consistency. Understanding the PostgreSQL table creation process is essential for
5 min read
PostgreSQL - CREATE TABLE AS
The CREATE TABLE AS statement in PostgreSQL is a powerful tool used to create a new table and populate it with data returned by a query. This functionality allows you to generate tables on the fly based on query results, which can be very useful for reporting, analysis, and other tasks. Let us bette
3 min read
PostgreSQL - Index On Expression
When working with databases, optimizing query performance is crucial, especially when dealing with large datasets. One powerful technique in PostgreSQL is leveraging indexes on expressions. This approach allows you to optimize queries that involve expressions, ensuring faster retrieval times and eff
3 min read
PostgreSQL - Generate Columns
When working with databases, there are scenarios where you need a columnâs value to be automatically computed based on other columns. In PostgreSQL, this can be achieved through generated columns. These special columns are calculated based on an expression using other columns in the table. The value
3 min read
PostgreSQL MERGE Statement
The MERGE statement in PostgreSQL is a powerful data manipulation tool introduced in PostgreSQL 15, enabling conditional INSERT, UPDATE, and DELETE operations in a single command. This feature streamlines data synchronization between tables, making it ideal for tasks such as upserts and handling tab
4 min read
CREATE TABLE in SQL Server
SQL Server provides a variety of data management tools such as querying, indexing, and transaction processing. It supports multiple programming languages and platforms, making it a versatile RDBMS for various applications. With its robust features and reliability, SQL Server is a popular choice for
4 min read