6

How can I return single row from postgresql function? What type should I use after returns? These is my code:

create or replace function get_perf()
returns ???? as $$  
select task_ext_perf.performance, task_ext_perf.unit from task_ext_perf order by task_ext_perf.tm limit 1; 
$$
language sql;
1
  • Returns record. Or if you return a row of a table, you can directly returns MyTable. Commented Jan 11, 2016 at 12:43

1 Answer 1

5

Considering a table User like this :

User
------
id
name

You can return a single row of a table with a procedure like this:

CREATE OR REPLACE function get_user()
RETURNS User AS $$  
  SELECT id, name
  FROM User
  WHERE id = 1
$$
language sql;

If you want to return a more elaborated row, you have to return a record, with OUT parameters.

CREATE FUNCTION get_user(OUT id integer, OUT name character varying, OUT linkedString character varying)
RETURNS record LANGUAGE sql AS $$
 SELECT
   u.id, u.name, ot.string
 FROM Users u
 INNER JOIN OtherTable ot ON ot.user_id = u.id
 WHERE id = 1
$$; 
Sign up to request clarification or add additional context in comments.

4 Comments

My example was simplified. I need to return several fields from different tables, not just one row from one table.
@IrS, I added an example with a procedure that returns a record.
How does one return a single row with plpgsql?
how would you do this if you were using EXECUTE _sql?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.