'Is there a better Postgres query to fetch top first rows in a group?

I have four tables foo, bar, baz, and qux

foo:

foo

bar:

bar

baz:

baz

qux:

qux

I'm looking for an output like:

output


I've written this query with minimal joins but I don't know of a way to optimize it. There's going to be 100k+ records in bar. I just need the first row from bar whose column bar1 matches with foo2 in foo

SELECT DISTINCT ON (foo_pk)
    foo_pk,
    foo1,
    qux1,
    bar_str.r1,
    bar_str.r2,
    bar_str.r3,
    (
        SELECT
            string_agg(CONCAT_WS(' ', baz_pk, baz2, baz3), ' | ')
        FROM
            baz
        WHERE
            baz1 = foo_pk
        GROUP BY
            baz1
    )
FROM
    foo
    JOIN qux ON qux_pk = foo2
    JOIN (
        SELECT
            RIGHT(bar3, 1) AS r1,
            RIGHT(bar3, 2) AS r2,
            RIGHT(bar3, 3) AS r3,
            bar1
        FROM
            bar
        ORDER BY
            bar1,
            bar2
    ) AS bar_str ON bar_str.bar1 = foo2
ORDER BY foo_pk

db fiddle link

I'm running Postgres v11.9 btw.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source