1

I have a table with more than 100000 rows and i want to sort them alphabetically using surname and name . I want to achieve the sort by using an index . I've tried this :

CREATE INDEX idx0 ON "People"(surname,name DESC NULLS LAST);

But the table is not sorted correctly . What am I doing wrong?

3
  • 1
    The index will speed up searches and order by. However, it will not re-order the physical table. I.e you still have to add an ORDER BY clause. Commented May 5, 2017 at 12:41
  • 1
    Tables represent unordered sets. If you want results in a particular order, you need to use order by on a query. Commented May 5, 2017 at 12:44
  • are you looking for CLUSTER command? keep in mind it is one time operation - later rows will unsort again Commented May 5, 2017 at 13:18

1 Answer 1

2

If you want to select data from table in this order, you should execute a query:

SELECT * FROM People ORDER BY surname, name DESC NULLS LAST

This query will run fast, because database will use index instead of sorting data on the fly (note, that it works only if columns and sorting directions of query's ORDER BY matches exactly with columns and sorting directions of index).

If you want to reorder data in table physically, then you can execute:

CLUSTER People USING idx0

But keep in mind that CLUSTER command will only reorder existing data. If you insert new data into table, it will not be placed in desired order, so you will have to execute CLUSTER command again.

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

Comments

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.