Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order a SELECT by the first element of an array?

Tags:

postgresql

I have an array of strings as one of my columns, and I want to sort the result by the first element of the array. This is what I have tried:

SELECT * FROM items ORDER BY aliases[0];

This did not work. How may this be accomplished?

like image 537
Michael Smith Avatar asked Feb 05 '23 03:02

Michael Smith


1 Answers

Arrays in Postgres are indexed beginning at position 1, not 0. From the documentation:

By default PostgreSQL uses a one-based numbering convention for arrays, that is, an array of n elements starts with array[1] and ends with array[n].

With this in mind, try the following query:

SELECT * FROM items ORDER BY aliases[1];
like image 102
Tim Biegeleisen Avatar answered Mar 12 '23 02:03

Tim Biegeleisen