Question

For a query that has no order by clause, will a given query plan always return results in the same order? I understand that a different plan may be chosen, but if the same plan is chosen, will that give the same result order? Essentially, what freedom does the query executor have to reorder the rows when executing a given plan?

Was it helpful?

Solution

No, results won't be returned in the same order, even without a plan change. The query executor does not have to reorder the rows, it doesn't even order them in the first place.

For example, when rows come in disk order:

CREATE TABLE o(id int);
INSERT INTO o VALUES (1),(2),(3);
ANALYZE o;
EXPLAIN SELECT * FROM o;
                   QUERY PLAN                    
-------------------------------------------------
 Seq Scan on o  (cost=0.00..1.03 rows=3 width=4)

SELECT * FROM o;

Result:

 id 
----
  1
  2
  3

Let's update a row (without even changing the value):

UPDATE o SET id=2 WHERE id=2;

and rerun the same select:

SELECT * FROM o;
 id 
----
  1
  3
  2

Notice how the order has changed. Of course the plan is still the same:

EXPLAIN SELECT * FROM o;
                   QUERY PLAN                    
-------------------------------------------------
 Seq Scan on o  (cost=0.00..1.03 rows=3 width=4)

Conclusion: the execution plan doesn't imply any order without order by.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top