Skip to content

Instantly share code, notes, and snippets.

@mknparreira
Last active August 12, 2021 22:09
Show Gist options
  • Save mknparreira/9c0aba8e90649aa2f7a2ed7540eae85e to your computer and use it in GitHub Desktop.
Save mknparreira/9c0aba8e90649aa2f7a2ed7540eae85e to your computer and use it in GitHub Desktop.
PostgreSQL | 9.2 row_to_json() with nested joins
SELECT
        json_build_object(
                'id', u.id,
                'name', u.name,
                'email', u.email,
                'user_role_id', u.user_role_id,
                'user_role', json_build_object(
                        'id', ur.id,
                        'name', ur.name,
                        'description', ur.description,
                        'duty_id', ur.duty_id,
                        'duty', json_build_object(
                                'id', d.id,
                                'name', d.name
                        )
                )
    )
FROM users u
INNER JOIN user_roles ur on ur.id = u.user_role_id
INNER JOIN role_duties d on d.id = ur.duty_id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment