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.
Code
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.
FAQ
- Which tables or CTEs does it reference?
- `probe_results`, `service_status` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.