I have a sql function that does a simple sql select statement:
CREATE OR REPLACE FUNCTION getStuff(param character varying)
RETURNS SETOF stuff AS
$BODY$
select *
from stuff
where col = $1
$BODY$
LANGUAGE sql;
For now I am invoking this function like this:
select * from getStuff('hello');
What are my options if I need to order and limit the results with order by
and limit
clauses?
I guess a query like this:
select * from getStuff('hello') order by col2 limit 100;
would not be very efficient, because all rows from table stuff
will be returned by function getStuff
and only then ordered and sliced by limit.
But even if I am right, there is no easy way how to pass the order by argument of an sql language function. Only values can be passed, not parts of sql statement.
Another option is to create the function in plpgsql
language, where it is possible to construct the query and execute it via EXECUTE
. But this is not a very nice approach either.
So, is there any other method of achieving this?
Or what option would you choose? Ordering/limiting outside the function, or plpgsql?
I am using postgresql 9.1.
Edit
I modified the CREATE FUNCTION statement like this:
CREATE OR REPLACE FUNCTION getStuff(param character varying, orderby character varying)
RETURNS SETOF stuff AS
$BODY$
select t.*
from stuff t
where col = $1
ORDER BY
CASE WHEN $2 = 'parent' THEN t.parent END,
CASE WHEN $2 = 'type' THEN t."type" END,
CASE WHEN $2 = 'title' THEN t.title END
$BODY$
LANGUAGE sql;
This throws:
ERROR: CASE types character varying and integer cannot be matched
?áDKA 13: WHEN $1 = 'parent' THEN t.parent
The stuff
table looks like this:
CREATE TABLE stuff
(
id integer serial,
"type" integer NOT NULL,
parent integer,
title character varying(100) NOT NULL,
description text,
CONSTRAINT "pkId" PRIMARY KEY (id),
)
Edit2
I have badly read Dems code. I have corrected it to question. This code is working for me.
Question&Answers:
os