[파이썬] SQLAlchemy CTE (Common Table Expressions) 활용

In this blog post, we will explore the usage of Common Table Expressions (CTEs) in SQLAlchemy, a powerful Python SQL toolkit and Object-Relational Mapping (ORM) library. CTEs allow us to define temporary named result sets within a SQL statement, making complex queries easier to read, write, and maintain.

What are Common Table Expressions?

Common Table Expressions (CTEs) are a SQL feature that allows us to create temporary named result sets within a query. These result sets, similar to temporary tables, can be referenced multiple times in a query, allowing for easier and more efficient complex queries.

CTEs are particularly useful in scenarios where we need to perform multiple calculations or transformations on data before using it in the final query. They help break complex problems into simpler, more manageable parts.

Using CTEs in SQLAlchemy

To use CTEs in SQLAlchemy, we need to import the from sqlalchemy.sql import text module, which provides support for textual SQL expressions. We can then define a CTE using the text() function and incorporate it into our query.

Let’s consider an example scenario where we have two tables: employees and departments. We want to retrieve the names and salaries of employees who belong to a specific department, along with the average salary of that department.

from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker

# Create an engine and establish a session
engine = create_engine('your_database_connection_url')
Session = sessionmaker(bind=engine)
session = Session()

# Define the CTE
cte = text('''
    WITH department_avg AS (
        SELECT department_id, AVG(salary) AS avg_salary
        FROM employees
        GROUP BY department_id
    )
    SELECT e.name, e.salary, da.avg_salary
    FROM employees e
    JOIN department_avg da ON e.department_id = da.department_id
    WHERE e.department_id = :dept_id
''')

# Execute the query with CTE
result = session.execute(cte, {'dept_id': 1})

# Fetch and print the results
for row in result:
    print(row.name, row.salary, row.avg_salary)

In the above code, we define our CTE using the text() method and the WITH clause. We then join the CTE with the employees table on the department_id column, filter the results based on the department ID, and retrieve the required columns (name, salary, and avg_salary).

By using CTEs, we can separate the logic for calculating the average salary into a separate block of SQL code, improving the readability and clarity of our query.

Conclusion

Common Table Expressions (CTEs) are a powerful tool for simplifying complex queries and improving the readability of SQL statements. SQLAlchemy provides support for CTEs using the text() function, making it easier for Python developers to leverage this feature.

By utilizing CTEs in SQLAlchemy, we can break down complex problems into smaller, more manageable parts, resulting in more efficient and maintainable code.

Give SQLAlchemy CTEs a try in your next project and see how they can simplify your SQL queries. Happy coding!