Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

7 of 7
Commonmark migration
CREATE FUNCTION samplefunc() 
 RETURNS TABLE(ntested int, rawscore int, growth int) AS
$func$
SELECT count(DISTINCT r.student_id) -- AS NTested
 ,avg(r.raw_score)::int -- AS RawScore
 ,avg(r.growth)::int -- AS Growth
FROM reports_results r
WHERE r.test_type_id = 1
AND r.test_id = '201403MAME04'
$func$ LANGUAGE sql;
  • The clause to return a table is RETURNS TABLE.

  • Carefully avoid conflicts between OUT parameters and column names. (I had such a conflict in my first draft). Table-qualify columns to disambiguate. All field names in RETURNS TABLE are effectively OUT parameters and visible inside the function (almost) everywhere.

Also:

If the query is guaranteed to return a single row, you might want to combine OUT parameters with RETURNS record:

CREATE FUNCTION samplefunc(OUT ntested int, OUT rawscore int, OUT growth int) 
 RETURNS record AS ...

The subtle difference: This way you get a single row with NULL values if nothing is found, where the first form would return nothing / no row.

Add IN parameters (request in comment)

CREATE FUNCTION samplefunc(_test_type_id int, _test_id text) 
 RETURNS TABLE(ntested int, rawscore int, growth int) AS
$func$
SELECT count(DISTINCT r.student_id)
 ,avg(r.raw_score)::int
 ,avg(r.growth)::int
FROM reports_results r
WHERE r.test_type_id = 1ドル -- or: = _test_type_id in Postgres 9.2+
AND r.test_id = 2ドル -- or: = _test_id
$func$ LANGUAGE sql;

Many related answers here on SO with more code examples. Like:

Try a search.

Erwin Brandstetter
  • 669.1k
  • 160
  • 1.2k
  • 1.3k

AltStyle によって変換されたページ (->オリジナル) /