개요
2025.06.24-[Python] SQLAlchemy - INSERT 하기에서 SQLAlchemy를 사용해 데이터를 테이블에 삽입했다. 이번 글에서는 테이블에 저장한 데이터를 조회해보려고 한다.
SELECT
select() 함수는 insert() 함수와 동일한 방식으로 작성한다.
from sqlalchemy import select
stmt = select(user_table).where(user_table.c.name == "spongebob")
print(stmt.compile())
다른 SQL문과 동일하게 구문을 실제로 실행할 때는 execute() 함수에 전달한다. SELECT문의 경우에는 행을 반환하기 때문에 실행 결과로 반환받은 객체를 순회해서 데이터에 접근할 수 있다.
조회할 컬럼을 명시적으로 지정할 때는 select() 함수로 조회할 테이블의 컬럼을 전달하면 된다. 테이블을 전달하면 테이블의 모든 컬럼을 조회한다.
from sqlalchemy import insert
stmt = select(user_table.c.fullname).where(user_table.c.name == "spongebob")
print(stmt.compile())
조회할 컬럼에 alias(AS 키워드)를 주고 싶을 때는 컬럼에 label() 함수를 사용한다.
from sqlalchemy import insert
stmt = select(user_table.c.fullname.label("username")).where(user_table.c.name == "spongebob")
print(stmt.compile())
상수 SELECT
SQL을 사용하다보면 아래와 같이 상수를 SELECT 하는 경우도 있다.
SELECT "TEST"
이 경우는 select() 함수 내에 test()나 literal_column()을 사용할 수 있다.
from sqlalchemy import text
from sqlalchemy import literal_column
print(select(text("TEST")).compile())
print(select(literal_column("TEST")).compile())
참고 문서
https://docs.sqlalchemy.org/en/20/tutorial/data_select.html
728x90