← Back to SQL, page 1

sql-0012 · Easy fresher

A query without ORDER BY has always returned rows in insert order. Is it safe to rely on that?

No. A table is an unordered set, and without ORDER BY the database may return rows in any order. The order you see comes from how rows are stored and which plan is chosen, and it can change after an index is added, data is updated, the table is vacuumed or the engine is upgraded.

Full answer

Relational tables have no built-in row order. When you omit ORDER BY, you are telling the database "any order is fine", and it will return rows in whatever order is cheapest for the plan it picked.

That order often looks like insert order on a small, fresh table, because the engine is reading pages from start to end. Many things can change it:

  • An index is added, and the planner starts reading through the index instead.
  • Rows are updated or deleted, and new rows reuse freed space in the middle of the table.
  • PostgreSQL runs a parallel scan, and workers return rows as they finish.
  • A JOIN switches from a nested loop to a hash join.

A tiny demonstration. Three members are inserted in the order Zara, Amit, Maya, and a plain read returns them in that order:

sql
CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
INSERT INTO members (name) VALUES ('Zara'), ('Amit'), ('Maya');
SELECT name FROM members;
name
Zara
Amit
Maya

Now add an index on name and ask for the same rows with a harmless filter. The planner answers from the index, so the rows come back in index order:

sql
CREATE INDEX idx_members_name ON members(name);
SELECT name FROM members WHERE name > '';
name
Amit
Maya
Zara
sql
EXPLAIN QUERY PLAN SELECT name FROM members WHERE name > '';
text
QUERY PLAN
SEARCH members USING COVERING INDEX idx_members_name (name>?)

Nothing about the data changed, but the "natural" order did. If the order matters to the user, to a test, or to pagination, write ORDER BY, and end it with a unique column so ties are resolved too.

sql
CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
INSERT INTO members (name) VALUES ('Zara'), ('Amit'), ('Maya');
SELECT name FROM members;

CREATE INDEX idx_members_name ON members(name);
SELECT name FROM members WHERE name > '';

EXPLAIN QUERY PLAN SELECT name FROM members WHERE name > '';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Tables are unordered sets
  • Without ORDER BY, the order depends on the plan
  • Adding an index can change the order you see
  • Always end ORDER BY with a unique key when order matters

Common mistakes

  • Writing tests that compare query output without ORDER BY
  • Paginating with LIMIT and OFFSET but no ORDER BY

Follow-ups

  • Why can LIMIT without ORDER BY return different rows on different runs?
  • What is a stable sort key?

Tips

  • Give one concrete cause of order changing, such as a new index