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.

SqlData Fetching

Code

snippet
-- 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

FAQ

Which objects does the SQL touch?
The references are `orders`, `customers`, `recent_orders`, `information_schema.routines`, with one join tying the pair together.