본문으로 바로가기

Order by 제외시 정렬 기준

category DataBase/MySQL 2019. 12. 24. 14:20
반응형


Order by를 사용하지 않으면 어떻게 정렬될까?

몇일전 회사에서 본부로부터 질문 하나를 받았습니다. 

url을 주면서 "이 페이지 정렬 기준 설정하는게 없는데 현재는 정렬이 어떻게 되고 있는거에요?"
페이지에 나오는 데이터 쿼리문을 찾아가 확인해봤는데 ORDER BY가 없는 SELECT 문이었습니다.
저는 "데이터베이스 자체에서 정렬을 해서 가져오는거 같아요" 라고 답변했습니다. 

이유는 쿼리를 가져와 조회해보니 결과값이 primary_key를 가지고 정렬이 되어 있는것처럼 보였기 떄문입니다.
애매한 대답을 하니 본부에서도 "그럼 입력한 순서대로 나온다고 봐도 될까요?" 라는 질문에 급하게 찾아서 답변을 드렸습니다.

 

찾아본 url에서는 

What is The Default Sort Order of SELECTS with no ORDER BY Clause?

* Do not depend on order when ORDER BY is missing.
* Always specify ORDER BY if you want a particular order -- in some situations the engine can eliminate the ORDER BY because of how it does some other step.
* GROUP BY forces ORDER BY. (This is a violation of the standard. It can be avoided by using ORDER BY NULL.)
SELECT * FROM tbl -- this will do a "table scan". If the table has never had any DELETEs/REPLACEs/UPDATEs, the records will happen to be in the insertion order, hence what you observed.
If you had done the same statement with an InnoDB table, they would have been delivered in PRIMARY KEY order, not INSERT order. Again, this is an artifact of the underlying implementation, not something to depend on.

ORDER BY 절이없는 SELECT의 기본 정렬 순서는 무엇입니까?

 

* ORDER BY가 누락 된 경우 주문에 의존하지 마십시오.

* 특정 주문을 원할 경우 항상 ORDER BY를 지정하십시오. 어떤 상황에서는 엔진이 다른 단계를 수행하는 방식으로 ORDER BY를 제거 할 수 있습니다.

* GROUP BY는 ORDER BY를 강제합니다. (이것은 표준을 위반하는 것입니다. ORDER BY NULL을 사용하면 피할 수 있습니다.)

SELECT * FROM tbl- "테이블 스캔"을 수행합니다. 테이블에 DELETEs / REPLACEs / UPDATEs가없는 경우 레코드는 삽입 순서대로 표시되므로 관찰 한대로 수행됩니다.

InnoDB 테이블로 동일한 명령문을 수행 한 경우 INSERT 순서가 아닌 PRIMARY KEY 순서로 전달되었을 것입니다. 다시 말하지만 이것은 기본 구현의 결과이며 의존해야 할 것이 아닙니다.

 

The default ordering will depend on indexes used in the query and in what order they are used. It can change as the data/statistics change and the optimizer chooses different plans.
If you want the data in a specific order, use ORDER BY

 

기본 순서는 쿼리에 사용 된 인덱스와 사용되는 순서에 따라 다릅니다. 데이터 / 통계가 변경되고 옵티마이 저가 다른 계획을 선택함에 따라 변경 될 수 있습니다.

특정 순서로 데이터를 원하면 ORDER BY를 사용하십시오.

 

이렇게 명시되어 있습니다. 

데이터가 안정화되어 있다면 insert문, primary_key 순서라고 생각 할 수도 있지만 그것을 의존하면 안됩니다.

정렬이 필요한경우에는 ORDER BY 절을 사용해야 합니다.

 

https://forums.mysql.com/read.php?21,239471,239688#msg-239688

 

MySQL :: Re: What is The Default Sort Order of SELECTS with no ORDER BY Clause?

Re: What is The Default Sort Order of SELECTS with no ORDER BY Clause? Posted by: Rick James Date: December 23, 2008 01:39AM * Do not depend on order when ORDER BY is missing. * Always specify ORDER BY if you want a particular order -- in some situations t

forums.mysql.com

반응형

'DataBase > MySQL' 카테고리의 다른 글

MySQL 날짜 더하기, 뺴기, 차이  (0) 2019.12.10