MySQL는 Order By가 없다면 정렬을 보장하지 않는다라는 글을 읽고 간략하게 정리한 글입니다.
이 글과는 별도로 해당 블로그에 좋은 글이 많으니 읽어보시면 좋을 것 같네요.
A cursor in the open state identifies a table, an ordering of the rows of that table, and a position relative to that ordering. If the <declare cursor> does not include an <order by clause>, or includes an <order by clause> that does not specify the order of the rows completely, then the rows of the table have an order that is defined only to the extent that the <order by clause> specifies an order and is otherwise implementation-dependent. When the ordering of a cursor is not defined by an <order by clause>, the relative positions of two rows is implementation- dependent. When the ordering of a cursor is partially determined by an <order by clause>, then the relative positions of two rows are determined only by the <order by clause>; if the two rows have equal values for the purpose of evaluating the <order by clause>, then their relative positions are implementation-dependent.
간략하게 요약하면 order by 를 정의하지 않을 경우 조회 순서가 보장되지 않음을 명세하고 있습니다.
ORDER BY 절이 없는 경우: 테이블의 행 순서는 데이터베이스 시스템의 구현에 따라 결정되며, 그 순서는 예측할 수 없고 보장되지 않습니다.
ORDER BY 절이 부분적으로만 지정된 경우: ORDER BY 절이 행의 일부만 정렬 기준으로 지정했다면, 나머지 행의 순서는 그 정렬 기준에 따라 동일한 값을 가지는 경우 구현에 따라 결정됩니다. 예를 들어, 두 행이 ORDER BY 절에서 동일한 값을 가지는 경우, 그 행들 간의 상대적인 순서는 보장되지 않으며, 시스템에 따라 달라질 수 있습니다.
커서기반 조회를 만들거나, 일반적인 offset 조회를 할 때 조회 순서가 보장되지 않을 수 있으니 order by를 꼭 사용해 순서를 보장합시다.