Db2 – Does DB2 order data by the primary key

db2order-by

I've recently had a discussion with a colleague who was pushing to remove order by clauses from a production query because the order by column was the same as the primary key.

After a lengthy discussion in which I tried to explain that he can't guarantee ordering based on the primary key the final conclusion was that he wasn't going to push for the MSSQL queries to be changed.
But he was still going to change the DB2 queries.

I couldn't immediately find an article disproving that DB2 orders queries by the primary key, and am currently wondering whether or not it does.

So my question is, how does DB2 order a query if there is no order by clause? Does it use the primary key?
How can you guarantee data is coming out ordered correctly, without an order by clause, in a parallel system?

Best Answer

No, your colleague is wrong.

All SQL proroducts - DBMS that behave according to the SQL standards - provide no guarantee that the result of a query output will be ordered in any way, unless there is an ORDER BY clause in the query.

As the IBM DB2 docs mention:

Ordering is performed in accordance with the comparison rules described in Language elements. The null value is higher than all other values. If your ordering specification does not determine a complete ordering, rows with duplicate values of the last identified sort-key have an arbitrary order. If you do not specify ORDER BY, the rows of the result table have an arbitrary order.