Last active
December 12, 2023 13:47
-
-
Save tomplex/d3f19c433ae125638e6c0fc155fdcee5 to your computer and use it in GitHub Desktop.
Postgres JSON/B array slice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Taken & expanded from https://stackoverflow.com/a/40377186/4453925 | |
*/ | |
drop function if exists json_sub_array(json, int, int); | |
create or replace function json_sub_array(json_array json, from_pos int, to_pos int) | |
returns json language sql as $$ | |
select json_agg(value) | |
from json_array_elements(json_array) with ordinality | |
where ordinality-1 between from_pos and to_pos | |
$$; | |
drop function if exists json_sub_array(json, int); | |
create or replace function json_sub_array(json_array json, from_pos int) | |
returns json language sql as $$ | |
select json_sub_array(json_array, from_pos, json_array_length(json_array)); | |
$$; | |
drop function if exists jsonb_sub_array(jsonb, int, int); | |
create or replace function jsonb_sub_array(jsonb_array jsonb, from_pos int, to_pos int) | |
returns jsonb language sql as $$ | |
select jsonb_agg(value) | |
from jsonb_array_elements(jsonb_array) with ordinality | |
where ordinality-1 between from_pos and to_pos; | |
$$; | |
drop function if exists jsonb_sub_array(jsonb, int); | |
create or replace function jsonb_sub_array(jsonb_array jsonb, from_pos int) | |
returns jsonb language sql as $$ | |
select jsonb_sub_array(jsonb_array, from_pos, jsonb_array_length(jsonb_array)); | |
$$; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment