from sqlalchemy import create_engine, MetaData, Table, Column, Integer, select
# Create an engine and connect to a database
engine = create_engine('your_database_connection_string')
conn = engine.connect()
# Define a table
metadata = MetaData()
my_table = Table('my_table', metadata,
Column('id', Integer, primary_key=True),
Column('name', String),
...
)
# Create a common table expression (CTE)
cte = my_table.cte('my_cte')
# Create a query using the CTE
query = select([cte.c.id, cte.c.name]).where(cte.c.id > 5)
# Execute the query
result = conn.execute(query)
# Process the result
for row in result:
print(row)
# Close the connection
conn.close()
In this example, my_table is defined as a Table object. We then create a CTE called my_cte using the cte method of my_table. We can then use my_cte in a query to select specific columns from the CTE and apply filters. Finally, we execute the query and process the result.