Possible Duplicate:
Why do results from a SQL query not come back in the order I expect?
From reading 7.5 Sorting Rows and from issues I've seen with PostgreSQL, my impression is the following, but that section is not fully explicit, so I would be grateful if someone could verify:
SELECT * FROM items;
has no guaranteed order.
SELECT * FROM items ORDER BY published_date ASC;
guarantees that two items with different dates come in a given order, but does not guarantee that two items with the same date always come in the same order.
SELECT * FROM items ORDER BY published_date ASC, id ASC;
always returns items in the same order, since it is fully deterministic.
Do I have this right?
I'm not quite clear about whether sorting on one attribute (such as published_date
) guarantees the order for records with the same value, as in the second example.
You have it right. The only order that is guaranteed is the order that your "ORDER BY" imposes. If there are permutations possible within that order these could all be a valid output.
The ORDER BY clause in PostgreSQL is used together with the SELECT statement to sort table data. The table data can either be sorted in ascending or descending order. By default, the data is sorted in ascending order.
PostgreSQL is a case-sensitive database by default, but provides various possibilities for performing case-insensitive operations and working with collations.
Order is not guaranteed unless you explicitly specify it with the ORDER BY
clause.
You might be getting data in the same order upon several executions in case there is no database activity, as PostgreSQL will just return rows in the order it finds them in the database pages. Do a small test:
In short: You might be even getting rows in the desired order, but this is just a coincidence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With