[TIL] SQL 쿼리에 ORDER BY문이 없을 때 출력 순서

김현진·2020년 8월 27일
0

SQL

목록 보기
2/4

MODE SQL Analytics Training: Understanding Search Functionality

서브쿼리를 하나씩 뜯어 넣던 중 ORDER BY절이 없는 쿼리를 만났다.

결과는 순서가 전혀 없어보였다. 어떤 칼럼으로도, 어떤 순서로도 정렬되었는지 파악이 되지 않았다. 평소 쿼리보다 출력된 테이블 결과에서 데이터에 대한 이해를 높이는 편이라 시간이나 유저 아이디 등 내가 납득할 수 있는 순서로 정리되지 않은 테이블을 보자 당황스러웠다.

구글에 sql order when no order by 라고 검색했고, 스택오버플로우에 나와 같은 고민을 가진 사람이 올린 게시물이 있었다.

When no 'ORDER BY' is specified, what order does a query choose for your record set?

Answer: "If you don't specify an ORDER BY, then there is NO ORDER defined." The results can be returned in an arbitrary order - and that might change over time, too. There is no "natural order" or anything like that in a relational database (at least in all that I know of). The only way to get a reliable ordering is by explicitly specifying an ORDER BY clause.

결론: ORDER BY문을 쓰지 않으면 ORDER가 없다. 유의미한 순서로 정렬하는 유일한 방법은 ORDER BY 문을 쓰는 것이다.

아래의 링크는 스택오버플로우에 위 답변을 단 사람이 추천한 아티클이다.

참고자료 1 No Seatbelt - Expecting Order without ORDER BY
(Conor Cunningham, Architect on the Core SQL Server Engine)
참고자료 2 Without ORDER BY, there is no default sort order
(Alexander Kuznetsov, 아티클을 읽으려면 sqlblog.com에 가입을 해야한다.)

profile
/* rise and shine */

0개의 댓글