18

How do I convert a simple select query like select * from customers into a stored procedure / function in pg?

I'm new to Postgres and create function customers() as returns table/setof just didn't feel right and thus the question here.

I understand procs are called "functions" in pg land. Thus create procedure does not exist and my only options are to either create a view or a function. The issue is create function x() returns setof y returns a paren'd comma separated row of values which can't be used without further processing (at least that's what I'm seeing in pgAdmin and Ruby/Sequel).

create function x() returns table(...) requires I embed the row definition which I don't want to.

I'm sure there's a reason behind all this but I'm surprised that the most common use case is this tricky.

2
  • 2
    @rebnoob Rather than "didn't work" - specify the full text of the function you tried and the resulting error message as well as your PostgreSQL version. Commented Jan 6, 2013 at 4:01
  • Great! Thank you Erwin and Craig. Commented Jan 7, 2013 at 3:04

2 Answers 2

23

Untested but should be about right:

CREATE OR REPLACE FUNCTION getcustomers() RETURNS SETOF customers AS $$
SELECT * FROM customers;
$$ LANGUAGE sql;
Sign up to request clarification or add additional context in comments.

2 Comments

this works, thank you. But pg seems to return just one column with comma sep'd values instead of actual columns, what gives?
@rebnoob You're calling it with something like SELECT x FROM getcustomers() x. You want to use SELECT getcustomers(); or SELECT * FROM getcustomers();.
22

The issue is "create function x() returns setof y" returns a paren'd comma separated row values which can't be used without further processing

The function returns a row. To decompose into individual columns, call it with:

SELECT * FROM getcustomers();

That's assuming the function defines a proper return type. See:

The manual on CREATE FUNCTION should be a good starting point. The example section covers this topic.

4 Comments

You sir.. are a jedi and force to reckon with!
Wasted 1 day to understand what was the problem. I was calling function without " * from" part and EF Core was giving error about db model mapping. Because data was comma, separated. Thanks :)
I get this a column definition list is required for functions returning "record"

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.