Using CTEs in PostgreSQL for Cleaner Efficient Queries

In the realm of SQL databases, PostgreSQL stands out with its rich feature set, one of which is Common Table Expressions (CTEs). CTEs offer a powerful way to simplify and structure complex queries, making them more readable and maintainable. This article explores the concept of CTEs in PostgreSQL, showcasing their utility through practical examples.

What are Common Table Expressions (CTEs)?

Common Table Expressions (CTEs) provide a method to create temporary result sets that can be referenced within a SELECT, INSERT, UPDATE, or DELETE statement. Think of a CTE as a named subquery that exists only for the duration of the query.

Advantages of Using CTEs

  1. Enhanced Readability: CTEs break down complex queries into manageable parts, making the logic easier to follow.
  2. Improved Maintainability: By segmenting a query into logical chunks, CTEs simplify debugging and maintenance.
  3. Reusability: CTEs can be referenced multiple times within the same query, reducing redundancy and improving efficiency.

Practical Example

Consider a scenario where you have an employee table structured as follows.

CREATE TABLE employees (
    name VARCHAR(100),
    department VARCHAR(50),
    salary NUMERIC

With sample data

INSERT INTO employees (name, department, salary) VALUES
('Alice', 'HR', 50000),
('Bob', 'HR', 60000),
('Charlie', 'Engineering', 70000),
('David', 'Engineering', 80000),
('Eve', 'Marketing', 55000);

Objective: Identify employees who earn more than the average salary in their department.

Using a CTE to Achieve This

Here's how you can leverage a CTE to accomplish this task:

WITH avg_salary AS (
    SELECT department, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY department
SELECT, e.department, e.salary, a.avg_salary
FROM employees e
JOIN avg_salary a ON e.department = a.department
WHERE e.salary > a.avg_salary;

Breakdown of the Query

  1. CTE Definition (avg_salary)
    • Compute the average salary for each department.
    • This creates a temporary result set named avg_salary with department and avg_salary columns.
  2. Main Query
    • Select employee details (name, department, salary) and include the average salary (avg_salary) from the CTE.
    • Join the employees' table with the CTE in the department column.
    • Filter out employees who earn more than the average salary in their respective departments.

Query Result

The query will produce a list of employees earning more than the average salary in their departments:

 name    | department  | salary | avg_salary 
 Bob     | HR          |  60000 |       55000
 Charlie | Engineering |  70000 |       75000


Common Table Expressions are a powerful feature in PostgreSQL that can greatly enhance the clarity and maintainability of your SQL queries. By structuring queries into logical, named parts, CTEs simplify complex operations, making your code more readable and easier to debug. Whether you're dealing with intricate data transformations or simply aiming to make your SQL more comprehensible, CTEs are an invaluable tool in your PostgreSQL arsenal.

Embrace the power of CTEs in your next PostgreSQL project and experience the benefits of cleaner, more efficient queries.

Similar Articles