Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6751309
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T12:54:41+00:00 2026-05-26T12:54:41+00:00

I have this function in PostgreSQL, but I don’t know how to return the

  • 0

I have this function in PostgreSQL, but I don’t know how to return the result of the query:

CREATE OR REPLACE FUNCTION wordFrequency(maxTokens INTEGER)
  RETURNS SETOF RECORD AS
$$
BEGIN
  SELECT text, count(*), 100 / maxTokens * count(*)
  FROM (
    SELECT text
    FROM token
    WHERE chartype = 'ALPHABETIC'
    LIMIT maxTokens
  ) AS tokens
  GROUP BY text
  ORDER BY count DESC
END
$$
LANGUAGE plpgsql;

But I don’t know how to return the result of the query inside the PostgreSQL function.

I found that the return type should be SETOF RECORD, right? But the return command is not right.

What is the right way to do this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T12:54:41+00:00Added an answer on May 26, 2026 at 12:54 pm

    Use RETURN QUERY:

    CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
      RETURNS TABLE (txt   text   -- also visible as OUT param in function body
                   , cnt   bigint
                   , ratio bigint)
      LANGUAGE plpgsql AS
    $func$
    BEGIN
       RETURN QUERY
       SELECT t.txt
            , count(*) AS cnt                 -- column alias only visible in this query
            , (count(*) * 100) / _max_tokens  -- I added parentheses
       FROM  (
          SELECT t.txt
          FROM   token t
          WHERE  t.chartype = 'ALPHABETIC'
          LIMIT  _max_tokens
          ) t
       GROUP  BY t.txt
       ORDER  BY cnt DESC;                    -- potential ambiguity 
    END
    $func$;
    

    Call:

    SELECT * FROM word_frequency(123);
    

    Defining the return type explicitly is much more practical than returning a generic record. This way you don’t have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

    Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
      • Select first row in each GROUP BY group?
    2. Repeat the expression ORDER BY count(*).
    3. (Not required here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
      • Naming conflict between function parameter and result of JOIN with USING clause

    Don’t use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples, you may want more explicit names.

    Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) – data type after name.

    While working with integer division, it’s better to multiply first and divide later, to minimize the rounding error. Or work with numeric or a floating point type. See below.

    Alternative

    This is what I think your query should actually look like (calculating a relative share per token):

    CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
      RETURNS TABLE (txt            text
                   , abs_cnt        bigint
                   , relative_share numeric)
      LANGUAGE plpgsql AS
    $func$
    BEGIN
       RETURN QUERY
       SELECT t.txt, t.cnt
            , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
       FROM  (
          SELECT t.txt, count(*) AS cnt
          FROM   token t
          WHERE  t.chartype = 'ALPHABETIC'
          GROUP  BY t.txt
          ORDER  BY cnt DESC
          LIMIT  _max_tokens
          ) t
       ORDER  BY t.cnt DESC;
    END
    $func$;
    

    The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery. Pretty, but a subquery is typically cheaper in simple cases like this one (mostly before Postgres 12).

    A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

    round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this function: Program A public ICollection<ReportLocationInfo> GetAllReportsInstalled() { return _Reports; } I
I am using Postgresql 8.3 and have the following simple function that will return
I have this function in my Javascript Code that updates html fields with their
I have this function in my head: <head> window.onload = function(){ var x =
I have this function from a plugin (from a previous post) // This method
I have this function... private string dateConvert(string datDate) { System.Globalization.CultureInfo cultEnGb = new System.Globalization.CultureInfo(en-GB);
I have this function: RegisterGlobalHotKey(Keys.F6, MOD_SHIFT | MOD_CONTROL); which call an API to register
I have this function to read in all ints from the file. The problem
I have this function: public bool IsValidProduct(int productTypeId) { bool isValid = false; if
I have this function signature I have to match typedef int (*lua_CFunction) (lua_State *L);//target

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.