Video in progress

Does a query without `ORDER BY` always return rows in the same order?

No. Without ORDER BY, SQL guarantees no order at all. Today the rows may come back in insertion order, and tomorrow an UPDATE, a VACUUM or a different plan shuffles them.

📖 Answer

On a local database with 20 rows everything comes out "by id", and people start to rely on it. On prod:

  • an UPDATE writes the new version of a row to a different page, so a Seq Scan finds it somewhere else;
  • the planner picks a Hash Join or a parallel scan instead of an Index Scan;
  • in PostgreSQL, because of synchronize_seqscans, a second Seq Scan may start reading from the middle of the table.

The result: with pagination, one row shows up on two pages and another never appears at all.

-- wrong: the order isn't guaranteed
SELECT * FROM products LIMIT 20 OFFSET 40;

-- right: the order is explicit and unique
SELECT * FROM products ORDER BY created_at DESC, id DESC LIMIT 20 OFFSET 40;

The second column (id) isn't there for nothing: the order among rows with the same created_at also has to be defined. Otherwise the problem is smaller, but it still shows up.

Calling findAll(PageRequest.of(page, 20)) without a Sort in Java is the same mistake.