PostgreSQL Parameterized Order By / Limit in Table Function
The question explores options for incorporating order by and limit clauses within a PostgreSQL table function, highlighting the potential inefficiency of ordering and slicing outside the function.
One solution presented is the use of a plpgsql function, which allows for more complex query construction and execution via EXECUTE. This approach offers greater flexibility and control over the query.
To implement this, a modified plpgsql function can be created:
CREATE OR REPLACE FUNCTION get_stuff(_param text, _orderby text, _limit int) RETURNS SETOF stuff AS $func$ BEGIN RETURN QUERY EXECUTE ' SELECT * FROM stuff WHERE col = ORDER BY ' || quote_ident(_orderby) || ' ASC LIMIT ' USING _param, _limit; END $func$ LANGUAGE plpgsql;
This function can be called as follows:
SELECT * FROM get_stuff('hello', 'col2', 100);
This solution avoids SQL injection vulnerabilities by using quote_ident() for identifiers and the USING clause for parameter values. Additionally, RETURN QUERY EXECUTE efficiently returns the query results.
While a plpgsql function may be more verbose than a simple SQL function, it provides greater flexibility and performance for more complex queries.
The above is the detailed content of How Can I Efficiently Implement Parameterized ORDER BY and LIMIT Clauses in a PostgreSQL Table Function?. For more information, please follow other related articles on the PHP Chinese website!