RETURNS TABLE Functions Act As Views
Wrap a parameterized query in RETURNS TABLE so callers can select from it and join or aggregate the result like a view.
Code
-- RETURNS TABLE:把查询封装成可参数化的“视图函数”
CREATE OR REPLACE FUNCTION recent_orders(p_limit integer)
RETURNS TABLE (order_id bigint, customer text, total numeric, placed_at timestamptz)
LANGUAGE sql
STABLE
AS $$
SELECT o.id, c.name, o.total, o.placed_at
FROM orders o
JOIN customers c ON c.id = o.customer_id
ORDER BY o.placed_at DESC
LIMIT p_limit;
$$;
-- 像表一样在 FROM 中使用,并可继续过滤
SELECT * FROM recent_orders(5);
SELECT customer, SUM(total) AS spent
FROM recent_orders(50)
GROUP BY customer
ORDER BY spent DESC;
-- 与视图的差异:函数可以接收参数
SELECT routine_name, data_type
FROM information_schema.routines
WHERE routine_name = 'recent_orders';How it works
The file runs SELECT / CREATE statements, touching orders, customers, recent_orders and information_schema.routines.
Mechanically, the statements are built from: one JOIN combining rows across tables; a WHERE clause narrowing which rows one statement affects; SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.
Applying it
Run the statement against the orders table; the LIMIT keeps the probe cheap while you tune the predicates.
Statements that matter
CREATE OR REPLACE FUNCTION recent_orders(p_limit integer)
RETURNS TABLE (order_id bigint, customer text, total numeric, placed_at timestamptz)
LANGUAGE sql
STABLE
AS $$
SELECT o.id, c.name, o.total, o.placed_at
FROM orders o
JOIN customers c ON c.id = o.customer_id
ORDER BY o.placed_at DESC
LIMIT p_limit;
$$;
SELECT routine_name, data_type
FROM information_schema.routines
WHERE routine_name = 'recent_orders';
SELECT customer, SUM(total) AS spent
FROM recent_orders(50)
GROUP BY customer
ORDER BY spent DESC;
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.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.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.
FAQ
- Which objects does the SQL touch?
- The references are `orders`, `customers`, `recent_orders`, `information_schema.routines`, with one join tying the pair together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.