HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Returning a json array slice in PostgreSQL

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlarrayreturningjsonslice

Problem

Postgres 9.5

Given a table with one field of type json, about 700 rows, and where each row has about 4,000 elements in a single array...

my_db_field:

[0.44577, 0.4855, 0.45429, 0.54437,...]
[0.45012, 0.48698, 0.45715, 0.55337,...]
[0.47347, 0.49156, 0.46079, 0.56818,...]
[0.4936, 0.49835, 0.46086, 0.58195,...]
[0.51068, 0.50511, 0.46228, 0.59482,...]


The PostgreSQL docs show how you can query for a single element inside an array.

SELECT my_db_field->2 AS test FROM my_db_table


results:

test (of type json)
--------------------
0.4855
0.48698
0.49156
etc.


What I would like to do, though, is select multiple elements in the array and return that as an array in the same format the rows are. By multiple, I mean around 300 elements in the array; e.g., from element 0 to element 300. Does Postgres have a nice syntax for such a query?

Solution

In PostgreSQL 12, you can obtain JSONB array slice using the jsonb_path_query_array function:

SELECT jsonb_path_query_array('["a","b","c","d","e","f"]', '$[2 to 4]');
 jsonb_path_query_array
------------------------
 ["c", "d", "e"]
(1 row)

Code Snippets

SELECT jsonb_path_query_array('["a","b","c","d","e","f"]', '$[2 to 4]');
 jsonb_path_query_array
------------------------
 ["c", "d", "e"]
(1 row)

Context

StackExchange Database Administrators Q#163761, answer score: 9

Revisions (0)

No revisions yet.