Skip to content
Advertisement

SQL Function has no destination when called

I’m getting a success when creating the below function, but when I call it I receive an error stating there is no destination.

CREATE FUNCTION get_top_films() RETURNS int 
language PLPGSQL
AS $$
DECLARE top_films integer;
BEGIN
    SELECT i.film_id,
    COUNT(*)
    FROM rental r
        JOIN inventory i ON r.inventory_id=i.inventory_id
    GROUP BY 1
    ORDER BY COUNT(*) DESC
    LIMIT 10;
RETURN top_films;
END;
$$

Advertisement

Answer

CREATE FUNCTION get_top_films() RETURNS setof inventory.filmid%type
language sql
AS $$
    SELECT i.film_id
    FROM rental r
        JOIN inventory i ON r.inventory_id=i.inventory_id
    GROUP BY 1
    ORDER BY COUNT(*) DESC
    LIMIT 10
$$;

Language SQL: https://www.postgresql.org/docs/current/xfunc-sql.html
language plpgsql: https://www.postgresql.org/docs/current/plpgsql.html
Language sql is more easier to understand. your query is not dynamic, so it’s just a function and $$ query $$. setof inventory.filmid%type will make it more flexiable. If you filmid type change, this function no need to change.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement