How to efficiently select rows having a MIN date in postgres
===

I need to quickly select a value ( `baz` ) from the "earliest" ( `MIN(save_date)` ) rows grouped by an their `foo_id`. The following query returns the correct rows (well almost, it can return multiples for each foo_id when there are duplicate save_dates).


The `foos` table contains about 55k rows and the `samples` table contains about 25 million rows.

    CREATE TABLE foos (
        foo_id     int,
        val        varchar(40),
        # ref_id is a FK, constraint omitted for brevity
        ref_id     int
    )
    CREATE TABLE samples (
        sample_id  int,
        save_date  date,
        baz        smallint,
        # foo_id is a FK, constraint omitted for brevity
        foo_id     int
    )

    WITH foo ( foo_id, val ) AS (
            SELECT foo_id, val FROM foos
            WHERE foos.ref_id = 1
        ORDER BY foos.val ASC
        LIMIT 25 OFFSET 0
    )
    SELECT foo.val, firsts.baz
    FROM foo
    LEFT JOIN (
        SELECT A.baz, A.foo_id
        FROM samples A
        INNER JOIN (
            SELECT foo_id, MIN( save_date ) AS save_date
            FROM samples
            GROUP BY foo_id
        ) B
        USING ( foo_id, save_date )
    ) firsts USING ( foo_id )
    
This query currently takes over 100 seconds; I'd like to see this return in ~1 second (or less!).

**How can I write this query to be optimal?**