from sqlalchemy import selectwith engine.connect() as conn: # Select all columns stmt = select(user_table) result = conn.execute(stmt) for row in result: print(f"{row.id}: {row.name} - {row.fullname}") # Select specific columns stmt = select(user_table.c.name, user_table.c.fullname) result = conn.execute(stmt) for row in result: print(f"{row.name} - {row.fullname}") # With WHERE clause stmt = select(user_table).where(user_table.c.name == "spongebob") result = conn.execute(stmt) print(result.one())
The ORM uses the same select() construct but returns ORM objects:
from sqlalchemy import selectfrom sqlalchemy.orm import Sessionwith Session(engine) as session: # Select all User objects stmt = select(User) for user in session.scalars(stmt): print(user) # With WHERE clause using ORM attributes stmt = select(User).where(User.name == "spongebob") spongebob = session.scalars(stmt).one() print(f"Found: {spongebob.name}") # Select specific ORM attributes stmt = select(User.name, User.fullname) for row in session.execute(stmt): print(f"{row.name} - {row.fullname}")
Use session.scalars() when selecting full ORM entities. Use session.execute() when selecting specific columns.
from sqlalchemy import select, and_, or_with engine.connect() as conn: # WHERE with multiple conditions stmt = select(user_table).where( and_( user_table.c.name.like('s%'), user_table.c.fullname.isnot(None) ) ) # ORDER BY stmt = select(user_table).order_by(user_table.c.name.desc()) # LIMIT stmt = select(user_table).limit(5) result = conn.execute(stmt) for row in result: print(row)
from sqlalchemy import select, and_, or_from sqlalchemy.orm import Sessionwith Session(engine) as session: # WHERE with multiple conditions stmt = select(User).where( and_( User.name.like('s%'), User.fullname.isnot(None) ) ) # Using filter_by for equality stmt = select(User).filter_by(name="spongebob") # ORDER BY stmt = select(User).order_by(User.name.desc()) # LIMIT stmt = select(User).limit(5) for user in session.scalars(stmt): print(user)
Joining tables is fundamental for relational queries:
Core
ORM
from sqlalchemy import selectwith engine.connect() as conn: # Explicit JOIN stmt = select(user_table, address_table).join( address_table, user_table.c.id == address_table.c.user_id ) # Using join_from for clarity stmt = select(user_table.c.name, address_table.c.email_address).join_from( user_table, address_table ) result = conn.execute(stmt) for row in result: print(row)
from sqlalchemy import selectfrom sqlalchemy.orm import Sessionwith Session(engine) as session: # Join using relationship stmt = select(User).join(User.addresses) # Filter on joined table stmt = select(User).join(User.addresses).where( Address.email_address.like('%sqlalchemy.org') ) # Select from both entities stmt = select(User, Address).join(User.addresses) for user, address in session.execute(stmt): print(f"{user.name}: {address.email_address}")