Return SELECT query results in PostgreSQL function
In PostgreSQL, using functions to return the results of a SELECT query requires understanding the appropriate syntax and return type. We'll examine one of the provided functions and guide you on how to correctly retrieve query results.
The function in question wordFrequency
currently lacks a correct return statement. To solve this problem, we will use the RETURN QUERY
syntax.
Corrected function:
<code class="language-sql">CREATE OR REPLACE FUNCTION wordFrequency(_max_tokens integer) RETURNS SETOF RECORD AS $$ BEGIN RETURN QUERY SELECT text, count(*), 100.0 / _max_tokens * count(*) AS ratio FROM ( SELECT text FROM token WHERE chartype = 'ALPHABETIC' LIMIT _max_tokens ) AS tokens GROUP BY text ORDER BY count DESC; END; $$ LANGUAGE plpgsql;</code>
Key points:
RETURN QUERY
syntax allows you to directly return the results of a SELECT query. SETOF RECORD
indicates that the function will return a set of records. text
and count(*)
) must match the column names in the query. We added AS ratio
to give the third column an unambiguous name and avoid ambiguity. At the same time, change 100
to 100.0
to avoid precision loss caused by integer division. Call function:
<code class="language-sql">SELECT * FROM wordFrequency(123);</code>
Additionally, using RETURNS TABLE
to explicitly define the return type is more practical than returning a generic record because it eliminates the need to specify a list of column definitions for every function call. For example:
<code class="language-sql">CREATE OR REPLACE FUNCTION wordFrequency(_max_tokens integer) RETURNS TABLE (text TEXT, cnt BIGINT, ratio NUMERIC) AS $$ BEGIN RETURN QUERY SELECT text, count(*), 100.0 / _max_tokens * count(*) FROM ( SELECT text FROM token WHERE chartype = 'ALPHABETIC' LIMIT _max_tokens ) AS tokens GROUP BY text ORDER BY count DESC; END; $$ LANGUAGE plpgsql;</code>
Important Notes:
By following these steps, you can efficiently use functions in PostgreSQL to return the results of a SELECT query.
The above is the detailed content of How to Correctly Return SELECT Query Results from a PostgreSQL Function?. For more information, please follow other related articles on the PHP Chinese website!