The .select() method in SQLAlchemy is used to construct a SELECT statement for querying a database. It allows you to specify the columns and tables to retrieve data from and apply various filtering and sorting conditions.
Here are three examples that demonstrate using .select():
Example 1: Selecting All Columns From a Table
from sqlalchemy import select
from sqlalchemy.orm import sessionmaker
# SQLAlchemy session object named 'session'
# Define the table model
Base = declarative_base()
employee = class Employee(
id = Column(Integer, primary_key=True),
name = Column(String),
age = Column(Integer)
)
# Create a select statement to retrieve all columns from the 'employees' table
stmt = select(employee)
# Execute the select statement
result = session.execute(stmt)
# Iterate over the result to fetch the data
for row in result:
print(row)
In this example, with an existing SQLAlchemy session object named ‘session’ and a table named ‘employees’ with columns ‘id’, ‘name’, and ‘age’. There is also a defined model called Employee and its table name and columns are specified using SQLAlchemy.
Creating a select statement using select(Employee) to retrieve all columns from the ‘employees’ table. Here, Employee represents the table model defined earlier. The select statement constructs a query to fetch all the rows and columns from the ‘employees’ table, and calling session.execute(stmt) then executes the statement.
The result object obtained from the execution allows for iteration over the rows using a loop. In this example, the print statement displays each row of the retrieved data. Further, all of the values of individual columns are accessible using the column names as attributes of the row object (e.g., row.id, row.name, row.age).
Example 2: Selecting Specific Columns with a Filter Condition
from sqlalchemy import select
from sqlalchemy.orm import sessionmaker
# Create a select statement to retrieve 'name' and 'age' columns from the 'employees' table
stmt = select(Employee.name, Employee.age).where(Employee.age > 30)
# Execute the select statement
result = session.execute(stmt)
# Iterate over the result to fetch the data
for row in result:
print(row.name, row.age)
Continuing with the same ‘session’ object and the ‘employees’ table defined in the previous example, this example shows a select statement using select(Employee.name, Employee.age) to retrieve only the ‘name’ and ‘age’ columns from the ‘employees’ table. Additionally, a filter condition using .where(Employee.age > 30) retrieves only the rows where the ‘age’ column is greater than 30.
Executing the select statement with session.execute(stmt) retrieves the result set. It is also possible to iterate over the result set and access the values of the ‘name’ and ‘age’ columns for each row. In this example, the ‘name’ and ‘age’ values are printed using row.name and row.age.
Example 3: Applying Ordering and Limiting the Result Set
from sqlalchemy import select
from sqlalchemy.orm import sessionmaker
# Create a select statement to retrieve 'name' and 'age' columns from the 'employees' table
# Order the results by 'age' in descending order and limit the result to 5 rows
stmt = select(Employee.name, Employee.age).order_by(Employee.age.desc()).limit(5)
# Execute the select statement
result = session.execute(stmt)
# Iterate over the result to fetch the data
for row in result:
print(row.name, row.age)
In this example, again using the existence of the ‘session’ object and the ‘employees’ table a select statement is created using select(Employee.name, Employee.age) to retrieve the ‘name’ and ‘age’ columns from the ‘employees’ table. To control the order of the results using .order_by(Employee.age.desc()) sorts the rows by the ‘age’ column in descending order. Additionally, this limits the result set to 5 rows by using .limit(5).
Executing the select statement with session.execute(stmt) retrieves the result set, which contains the ordered and limited data. Iterating over the result set and accesses the ‘name’ and ‘age’ columns for each row. In this example the ‘name’ and ‘age’ values are printed.
These examples demonstrate how you can use the .select() method in SQLAlchemy to construct complex SELECT statements for querying databases. Remember to adapt the code to your specific database and table structures.
For more information about SQLAlchemy and the .select() method:
SQLAlchemy Documentation: The SQLAlchemy documentation examples of related constructs for the .select() method. https://docs.sqlalchemy.org/en/latest/core/selectable.html
SQLAlchemy Tutorial: The SQLAlchemy tutorial has step-by-step guidance on using SQLAlchemy for database operations, including querying with .select(). https://docs.sqlalchemy.org/en/latest/orm/tutorial.html
SQLAlchemy GitHub Repository: The SQLAlchemy GitHub repository contains some more resources related to SQLAlchemy. https://github.com/sqlalchemy/sqlalchemy