Mikhail
Mikhail

Reputation: 215

Priority in ORDER BY clause

When I use ORDER BY clause to sort table by one simple column, it ok. But also I know there is an opportunity to mix columns ins ORDER BY clause to sort. But how does it works? How postgres set priorities? (Perhaps, I do not know something, correct me please if I am wrong in some way).

Upvotes: 1

Views: 3454

Answers (2)

Andronicus
Andronicus

Reputation: 26046

The priority is in order of columns listed after order by, here's an example:

select col1, col2, col3 from table_name order by col1, col3, col2

|col1|col2|col3|
|   1|   1|   1|
|   1|   2|   1|
|   1|   1|   2|
|   1|   2|   2|
|   2|   1|   1|
|   2|   2|   1|
|   2|   1|   2|
|   2|   2|   2|

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1269623

The columns or expressions in an order by specify the ordering of the rows in the result set.

If you have multiple columns or expressions (called keys), the first key is used to sort the data. The second key is only used when there is a tie for the first key. Similarly, the third key is only used when there is a tie for the first two keys.

So, the result is a lot like a telephone book order by (lastname, firstname). The firstname is only used when there are multiple entries for the same lastname.

Upvotes: 5

Related Questions