개요
2025.06.25-[Python] SQLAlchemy - SELECT 하기에서 데이터베이스 테이블의 데이터를 조회하는 방법을 알아보았다. 이번 글에서는 조건에 맞는 데이터를 필터링하는 WHERE 절을 사용하는 방법을 적어둔다.
WHERE
WHERE 절은 Select.where() 메서드에 원하는 조건을 지정하여 생성할 수 있다.
from sqlalchemy import select
stmt = select(user_table).where(user_table.c.name == "spongebob")
print(stmt.compile())
AND
AND로 연결된 조건절을 생성할 때는 Select.where()을 필요한 만큼 호출한다.
from sqlalchemy import select
stmt = (select(user_table)
.where(user_table.c.name == "spongebob")
.where(user_table.c.fullname != ""))
print(stmt.compile())
또는 하나의 Select.where() 내에 여러 개의 조건을 전달해도 된다.
stmt = (select(user_table)
.where(user_table.c.name == "spongebob",
user_table.c.fullname != ""))
print(stmt.compile())
다른 방법으로는 and_() 함수를 직접 호출활 수 있다.
from sqlalchemy import and_
stmt = (select(user_table)
.where(and_(user_table.c.name == "spongebob",
user_table.c.fullname != "")))
print(stmt.compile())
OR
반면 OR 조건의 경우에는 or_ 함수를 사용해 명시적으로 지정해주어야 하는 것 같다.
from sqlalchemy import and_, or_
stmt = (select(user_table)
.where(or_(user_table.c.name == "spongebob",
user_table.c.fullname.startswith("Sandy"))))
print(stmt.compile())
참고 문서
https://docs.sqlalchemy.org/en/20/tutorial/data_select.html#the-where-clause
728x90