How does postgres order the results when ORDER BY is not provided

时间:2015-05-04 19:40:13

标签: sql postgresql select sql-order-by

Let's say I have two tables:

user (user_name varchar(50), project_name varchar(50))
project (project_name varchar(50), project_cost(integer))

I have a query that's returns me results which are "de-facto desired" :

select u.user_name, p.project_name 
from user u, project p 
where u.project_name = p.project_name

Postgres says that order of rows is not predictable when ORDER BY is not given. But yet in my local test, postgres returns rows in a same order for repeated tests.

Could you please help me understand what Postgres really does when order by is not provided in the query?

I don't have access to all the possible places where the real table and schema a live, so I really need to know what really happens in order to keep existing ordering intact.

3 个答案:

答案 0 :(得分:2)

If no order by clause is given, postgres (and any other reasonable database, for that sake), should return the rows in the order it was able to produce them (be it from an internal cache, an index, or directly from the table).

Since the same algorithm is used on the same data, it isn't surprising you're getting the same rows in the same order. However, this does not mean you should rely on this ordering. If you do something to change the data's layout on the disk (e.g., back it up and restore it, or even rebuild the tables' indexes), you're likely to get a different ordering.

答案 1 :(得分:1)

要知道DBMS究竟应该做什么,应该看看PLAN。输出顺序也取决于它。但是要记住两件事:首先,如果计划包括'完整(堆)表扫描',那么订单是未定义的(因为DBMS可以自由地重新排序堆数据);第二,如果您更改SQL语句或更新数据库统计信息,计划可能会发生重大变化。这就是为什么你不应该长期依赖输出顺序的稳定性。

答案 2 :(得分:0)

Probably in the order of the clustered index if the table has one. However this is not something that should be trusted, as the documentation say.