쿼리 결과 정렬

Python으로 배우는 데이터베이스 입문

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

ORDER BY 절

  • 쿼리 결과에서 레코드 반환 순서를 제어합니다
  • 구문 메서드 order_by()로 사용 가능
Python으로 배우는 데이터베이스 입문

오름차순 정렬

print(results[:10])
[('Illinois',), ...]
stmt = select([census.columns.state])

stmt = stmt.order_by(census.columns.state)
results = connection.execute(stmt).fetchall()
print(results[:10])
[('Alabama',), ...]
Python으로 배우는 데이터베이스 입문

내림차순 정렬

  • order_by()에서 열을 desc()로 감쌉니다
Python으로 배우는 데이터베이스 입문

다중 열 정렬

  • 여러 열은 쉼표로 구분합니다
  • 첫 번째 열로 전체 정렬
  • 첫 열에 중복이 있으면 두 번째 열로 정렬
  • 모든 열이 정렬될 때까지 반복
Python으로 배우는 데이터베이스 입문

다중 열 정렬

print(results)
('Alabama', 'M')
stmt = select([census.columns.state, census.columns.sex])

stmt = stmt.order_by(census.columns.state, census.columns.sex)
results = connection.execute(stmt).first() print(results)
('Alabama', 'F')
('Alabama', 'F')
...
('Alabama', 'M')
Python으로 배우는 데이터베이스 입문

연습해 봅시다!

Python으로 배우는 데이터베이스 입문

Preparing Video For Download...