D
D
DoggoTheKing2018-06-07 17:35:36
PostgreSQL
DoggoTheKing, 2018-06-07 17:35:36

How to sort records once and for all in PostgreSQL?

There is a table, it has integer columns A and B.
The table is sorted by column A. You need to make sure that the table is sorted by B.
ORDER BY is not suitable, because this is a one-time sort (as I understand it)

Answer the question

In order to leave comments, you need to log in

6 answer(s)
S
Sergey Gornostaev, 2018-06-07
@DoggoTheKing

PostgreSQL, like many other DBMSs, stores data in an arbitrary order. And he also selects them randomly, if the sorting rule is not set. All you can do is to build an index on the fields you are interested in so that the selection with sorting on these fields is performed quickly.

P
ponaehal, 2018-06-07
@ponaehal

I'm talking about Oracle, but I suspect that in all databases it's about the same
Once and for all sorting the data will not work. The data in the table is unsorted. It can be done artificially. Transfer the data to another table, then delete the data in the original table and fill it in from the second one in the right order. But this makes little sense - when someone else adds data to this table, your sort will go. In the general case, it is much more correct to use an index (the data is sorted in it) and make sure that it is used in queries.

D
d-stream, 2018-06-07
@d-stream

The wording of the question is identical to "I don't need the downloaded file, how can I upload it back to the Internet?"
For subd tables, the order of output on request is determined either explicitly by order by at each point in time, or as a subd is convenient, but each time in a different way. And the fact that often the spontaneous order is repeated is just an accident.
The only way is keys and indexes. With their competent construction, the output will be not only in the specified order, but in some cases faster.

K
ky0, 2018-06-07
@ky0

Sort into another table, delete the first one, rename it. But you don't have to do that.

A
alexalexes, 2018-06-07
@alexalexes

Create a view with the desired sorting and use it in all requests.

H
hardstep1983, 2020-09-24
@hardstep1983

cluster using
;
https://postgrespro.ru/docs/postgresql/9.6/sql-cluster

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question