Custom sort order with jsonb key

From: Anton Ananich <anton(dot)ananich(at)gmail(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Custom sort order with jsonb key
Date: 2016-06-23 18:38:54
Message-ID: 1BFCD444-70DD-4A32-B2AB-CEFCC2922419@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Dear colleagues,

I have a table in PostgreSQL with some data:

create table FOO (
key jsonb
);

insert into FOO(key) values ('[2014]');
insert into FOO(key) values ('[2015]');
insert into FOO(key) values ('[2016]');
insert into FOO(key) values ('[2014, 2]');
insert into FOO(key) values ('[2014, 2, 3]');
insert into FOO(key) values ('[2014, 3]');
insert into FOO(key) values ('[2014,2,4]');
insert into FOO(key) values ('[2014, 2,4]');
insert into FOO(key) values ('[2014,3,13]');
insert into FOO(key) values ('[2014, 2, 15]');

And I try to sort these rows like that:

SELECT key FROM FOO order by key;

The result is:

[2014]
[2015] <==
[2016] <==
[2014, 2]
[2014, 3] <==
[2014, 2, 3]
[2014, 2, 4]
[2014, 2, 4]
[2014, 2, 15]
[2014, 3, 13]

But what I need is

[2014]
[2014, 2]
[2014, 2, 3]
[2014, 2, 4]
[2014, 2, 4]
[2014, 2, 15]
[2014, 3] <==
[2014, 3, 13]
[2015] <==
[2016] <==

is there a way to achieve it?

Regards,
Anthony Ananich
http://ananich.pro <http://ananich.pro/>

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message David G. Johnston 2016-06-23 19:03:52 Re: Custom sort order with jsonb key
Previous Message Steve Midgley 2016-06-23 17:19:07 Re: [SQL] Regarding RDS postgresql instance