RETURN QUERY Accumulates Setof Rows

RETURN NEXT and RETURN QUERY append rows to the result set without leaving the function, so a PL/pgSQL function can mix hand-built rows with whole queries.

SqlData Fetching

Code

snippet
CREATE TABLE probe_results (
    endpoint   text,
    health_ok  boolean,
    checked_at timestamptz
);

INSERT INTO probe_results VALUES
    ('payments', true,  now() - interval '2 hours'),
    ('search',   false, now() - interval '3 hours');

CREATE OR REPLACE FUNCTION service_status() RETURNS TABLE (svc text, ok boolean)
LANGUAGE plpgsql AS $$
BEGIN
    -- RETURN NEXT 追加一行,函数并不退出
    svc := 'gateway';
    ok  := true;
    RETURN NEXT;

    -- RETURN QUERY 把整条查询的结果一次性追加进结果集
    RETURN QUERY
        SELECT endpoint, health_ok
        FROM probe_results
        WHERE checked_at >= now() - interval '1 day';

    -- RETURN QUERY EXECUTE:动态 SQL 同样可追加,USING 传参
    RETURN QUERY EXECUTE
        'SELECT $1, $2' USING 'fallback', false;

    RETURN;   -- 无参 RETURN(或落到函数末尾)才真正返回
END $$;

SELECT * FROM service_status();

Inside the snippet

SELECT / INSERT / CREATE statements share the script, touching probe_results and service_status.

Breaking the statements into their working parts: a WHERE clause that keeps only the rows a statement is meant to touch.

Putting it to use

Run the statement against the probe_results table.

Core lines

INSERT INTO probe_results VALUES
    ('payments', true,  now() - interval '2 hours'),
    ('search',   false, now() - interval '3 hours');
CREATE TABLE probe_results (
    endpoint   text,
    health_ok  boolean,
    checked_at timestamptz
);
SELECT * FROM service_status();

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`probe_results`, `service_status` — referenced directly, no join needed.