0

How can i make two SELECT's into two json arrays from the same table?

╔════╦══════════════╦
║ id ║  users       ║ 
╠════╬══════════════╬
║  1 ║ Jeff Atwood  ║
║  2 ║ Geoff Dalgas ║
║  3 ║ Jarrod Dixon ║
║  4 ║ Joel Spolsky ║ 
╚════╩══════════════╩

How to combine this two selects in one query?

First select example

SELECT JSON_AGG(arr1) as arr1
FROM (
  SELECT *
  FROM users
  WHERE id>1
) arr1

Second select example

SELECT JSON_AGG(arr2) as arr2
FROM (
  SELECT *
  FROM users
  WHERE id<2
) arr2

Exprected:

[arr1: [{id:1}, {id:2}], arr2: [{id:1}, {id:2}]]
7
  • The expected output is not valid JSON array syntax. What do you really want, an object? Commented Jul 22, 2020 at 13:54
  • @a_horse_with_no_name no, each of 2 selects should have different where Commented Jul 22, 2020 at 13:55
  • So, just SELECT json_agg(*) AS arr1, json_agg(*) AS arr2 FROM users? Commented Jul 22, 2020 at 13:56
  • That's not what your expected output shows Commented Jul 22, 2020 at 13:56
  • 1
    @ZiiMakc Separate row? Did you mean separate column? Commented Jul 22, 2020 at 13:57

1 Answer 1

1

You can use a conditional aggregation for that:

SELECT JSON_AGG(u) filter (where id > 1) as arr1,
       JSON_AGG(u) filter (where id < 2) as arr2
FROM users u

(online demo)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.