Skip to content

Help build nested queries #2

@patdx

Description

@patdx

Similar to this Postgres example: https://www.pgcasts.com/episodes/generating-json-from-sql

We can build a nested JSON response in sqlite something like this:

select json_object(
  'users',
  (
    select json_group_array(
      json_object('id', id, 'name', name, 'email', email, 'bookmarks', bookmarks)
    )
    from (
      select
        id,
        name,
        email,
        (
          select
            json_group_array(
              json_object(
                'id',
                id,
                'user_id',
                user_id,
                'name',
                name,
                'url',
                url
              )
            )
          from
            (
              select
                id,
                user_id,
                name,
                url
              from
                bookmarks
              where
                user_id = users.id
            )
        ) as bookmarks
      from
        users
    )
  )
) as json_result

The result will look like:

{
  "users": [
    {
      "id": 1,
      "name": "John",
      "email": "[email protected]",
      "bookmarks": [
        {
          "id": null,
          "user_id": 1,
          "name": "Hashrocket",
          "url": "https://www.hashrocket.com"
        },
        {
          "id": null,
          "user_id": 1,
          "name": "PostgreSQL Docs",
          "url": "http://www.postgresql.org/docs/current/static/index.html"
        }
      ]
    },
    {
      "id": 2,
      "name": "Jane",
      "email": "[email protected]",
      "bookmarks": [
        {
          "id": null,
          "user_id": 2,
          "name": "Google",
          "url": "https://www.google.com"
        },
        {
          "id": null,
          "user_id": 2,
          "name": "Stack Overflow",
          "url": "http://stackoverflow.com/"
        },
        {
          "id": null,
          "user_id": 2,
          "name": "YouTube",
          "url": "https://www.youtube.com"
        }
      ]
    }
  ]
}
  1. How can I facilitate building this query in the UI?
  2. Is this efficient/correct?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions