Іван Гладуш
Іван Гладуш

Reputation: 385

Ordering in selection result. Postgres

Does the sequence of records in SELECT QUERY in result always the same? I mean that if the first result of operation returns the following sequence: first record second record third record All other select * from t queries always return records in the same sequence.

Upvotes: 1

Views: 677

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269623

A SQL query -- like a SQL table -- represents an unordered set. There is no ordering, unless an ORDER BY is present for the outermost SELECT.

As an unordered set, the same query can return results in a different order each time it is run.

So, if you want results in a particular order, use ORDER BY.

I should add that if multiple rows have the same key, then these rows can appear in any order, even with an ORDER BY. In general, you should ensure that the keys in the ORDER BY uniquely define each row (say by including the primary key as the final key).

Upvotes: 6

Related Questions