SQL row return order

后端 未结 5 1605
失恋的感觉
失恋的感觉 2020-12-11 03:46

I have only used SQL rarely until recently when I began using it daily. I notice that if no \"order by\" clause is used:

  1. When selecting part of a table the row
5条回答
  •  情书的邮戳
    2020-12-11 03:59

    For PostgreSQL, if you omit the ORDER BY clause you could run the exact same query 100 times while the database is not being modified, and get one run in the middle in a different order than the others. In fact, each run could be in a different order.

    One reason this could happen is that if the plan chosen involves a sequential scan of a table's heap, and there is already a seqscan of that table's heap in process, your query will start it's scan at whatever point the other scan is already at, to reduce the need for disk access.

    As other answers have pointed out, if you want the data in a certain order, specify that order. PostgreSQL will take the requested order into consideration in choosing a plan, and may use an index that provides data in that order, if that works out to be cheaper than getting the rows some other way and then sorting them.

    GROUP BY provides no guarantee of order; PostgreSQL might sort the data to do the grouping, or it might use a hash table and return the rows in order of the number generated by the hashing algorithm (i.e., pretty random). And that might change from one run to the next.

提交回复
热议问题