1

I would like to organize my postgresql table in ascending order from the date it was created on. So I tried:

SELECT * 
FROM price
ORDER BY created_on; 

And it did show me the database in that order, however it did not save it.

Is there a way I can make it so it gets saved?

1 Answer 1

3

Tables in a relational database represent unordered sets. There is no such thing as the "order of rows" in a table.

If you need a specific sort order, the only way is to use an order by in a select statement as you did.

If you don't want to type the order by each time, you can create a view that does that:

create view sorted_price
as
select *
from price
order by created_on;

But be warned: if you sort the rows from the view in a different way, e.g. select * from sorted_price order by created_on desc Postgres will actually apply two sorts. The query optimizer is unfortunately not smart enough to remove the one store in the view's definition.

Sign up to request clarification or add additional context in comments.

5 Comments

As an optimisation, you can (a) create an index, although for listing the whole table it might not help much; or (b) CLUSTER the table, although that's a heavy operation and the order won't be maintained for new rows
So it created a new table... interesting... Thank you.
@pete: no, it's not a table. A view only stores the query, not data at all
@sabik: CLUSTER won't help as it will not guarantee any sort order. The only way to get a guaranteed sort order is to use order by. Without it the database is free to return the rows in any order it likes.
Yeah, CLUSTER is purely an optimisation, to potentially help the queries with ORDER BY run faster

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.