Function dosn't return value from insert - sql

I have this code:
CREATE OR REPLACE FUNCTION get_create_tagId(tagName text) RETURNS text AS $$
BEGIN
IF EXISTS(
SELECT * FROM tags WHERE tag = tagName)
THEN
RETURN(SELECT id FROM tags WHERE tag=tagName);
ELSE
INSERT INTO tags (tag) VALUES(tagName) RETURNING id;
END IF ;
END
$$ LANGUAGE plpgsql;
But when i run it i get
ERROR: query has no destination for result data
even though i have RETURNING id
What should i do/change?

You need to store the returned ID into a variable, then return that variable in the ELSE branch:
CREATE OR REPLACE FUNCTION get_create_tagid(p_tagnametext)
RETURNS text AS $$
DECLARE
l_id integer;
BEGIN
IF EXISTS(SELECT * FROM tags WHERE tag = p_tagname)
THEN
RETURN (SELECT id FROM tags WHERE tag = p_tagname);
ELSE
INSERT INTO tags (tag) VALUES(p_tagname)
RETURNING id
INTO l_id;
return l_id;
END IF ;
END
$$
LANGUAGE plpgsql;
If you have a unique index (or constraint) on the tag column (which you really should have), then you can simplify this:
with new_tag as (
insert into tags (tag)
values ('one')
on conflict do nothing
returning id
)
select id
from new_tag
union all
select id
from tags
where tag = 'one';
The insert won't return anything if the tag exists and thus the final select * from new_tag won't return a row, but second part of the union will. If the row did not exists, the final select from tags wouldn't see it and return no row.
This will be more efficient and safe from race conditions.
Of course you can put that into a function too:
CREATE OR REPLACE FUNCTION get_create_tagid(p_tagname text)
RETURNS text AS $$
$$
with new_tag as (
insert into tags (tag)
values (p_tagname)
on conflict do nothing
returning id
)
select id
from new_tag
union all
select id
from tags
where tag = p_tagname;
$$
LANGUAGE sql;

You can declare new variable and get tag_id into it and return. I supposed that id is autoincrement or serial data type.
CREATE OR REPLACE FUNCTION get_create_tagId(tagName text)
RETURNS text AS $$
DECLARE
tag_id INTEGER;
BEGIN
IF EXISTS(SELECT * FROM tags WHERE tag = tagName) THEN
tag_id := (SELECT id FROM tags WHERE tag=tagName);
RETURN tag_id;
ELSE
INSERT INTO tags(tag) VALUES(tagName);
tag_id := (SELECT max(id) FROM tags);
RETURN tag_id;
END IF;
END
$$ LANGUAGE plpgsql;

Related

Race Condition between SELECT and INSERT for multiple columns

Note: This is a question which is a follow up of this solution. You need to read the link to get context for this question. Also, this is for postgres v9.4
If we want to return multiple columns now instead of just 1 column, how can we achieve it?
Let's take a table t:
create table t(tag_id int, tag text unique);
Now this is what I want:
whenever I call a method f_tag_id, I want it to return all the columns for the unique row if it exists in the table t else insert it and return all the columns.
So these are the things I tried for the f_insert_tag
Option1:
CREATE OR REPLACE FUNCTION f_insert_tag(tag_p_id int, _tag text)
RETURNS TABLE(_tag_p_id int, _tag_ text)
AS
$func$
BEGIN
INSERT INTO t(tag_id,tag) VALUES (tag_p_id, _tag);
return query Select * from t where t.tag_id = tag_p_id;
EXCEPTION WHEN UNIQUE_VIOLATION THEN -- catch exception, NULL is returned
END
$func$ LANGUAGE plpgsql;
Option 2:
CREATE OR REPLACE FUNCTION f_insert_tag(tag_p_id int, _tag text, out _tag_id int, out _tag_ text)
AS
$func$
BEGIN
INSERT INTO t(tag_id,tag) VALUES (tag_p_id, _tag);
Select t.tag_id, t.tag from t where t.tag_id = tag_p_id into _tag_id, _tag_;
EXCEPTION WHEN UNIQUE_VIOLATION THEN -- catch exception, NULL is returned
END
$func$ LANGUAGE plpgsql;
Option 3:
CREATE OR REPLACE FUNCTION f_insert_tag(tag_p_id int, _tag text)
returns setof t AS
$func$
BEGIN
INSERT INTO t(tag_id,tag) VALUES (tag_p_id, _tag);
return query Select * from t where t.tag_id = tag_p_id;
EXCEPTION WHEN UNIQUE_VIOLATION THEN -- catch exception, NULL is returned
END
$func$ LANGUAGE plpgsql;
All the 3 worked by themselves:
select f_insert_tag(1322, 'helloworldaa');
f_insert_tag
---------------------
(1322,helloworldaa)
For the other function, f_tag_id as well I tried many methods:
Option 1:
CREATE OR REPLACE FUNCTION f_tag_id(tag_p_id int, _tag text, out _tag_id int, out _tag_ text)
AS
$func$
BEGIN
LOOP
SELECT t.tag_id, t.tag FROM t WHERE t.tag = _tag
UNION ALL
SELECT f_insert_tag(tag_p_id, _tag)
into _tag_id, _tag_;
EXIT WHEN _tag_id IS NOT NULL; -- else keep looping
END LOOP;
END
$func$ LANGUAGE plpgsql;
Option 2:
CREATE OR REPLACE FUNCTION f_tag_id(tag_p_id int, _tag text)
RETURNS table(_tag_id int, _tag_ text) AS
$func$
BEGIN
LOOP
SELECT t.tag_id, t.tag FROM t WHERE t.tag = _tag
UNION ALL
SELECT f_insert_tag(tag_p_id, _tag)
into _tag_id, _tag_;
EXIT WHEN _tag_id IS NOT NULL; -- else keep looping
END LOOP;
END
$func$ LANGUAGE plpgsql;
For both these, I got the same error:
select f_tag_id(22, 'test');
ERROR: each UNION query must have the same number of columns
LINE 3: SELECT f_insert_tag(tag_p_id, _tag)
^
QUERY: SELECT t.tag_id, t.tag FROM t WHERE t.tag = _tag
UNION ALL
SELECT f_insert_tag(tag_p_id, _tag)
CONTEXT: PL/pgSQL function f_tag_id(integer,text) line 5 at SQL statement
The wrench in the works is SELECT f_insert_tag(tag_p_id, _tag) instead of
SELECT * FROM f_insert_tag(tag_p_id, _tag)
For Postgres 9.4
CREATE FUNCTION f_insert_tag(_tag_id int, _tag text, OUT _tag_id_ int, OUT _tag_ text)
AS
$func$
BEGIN
INSERT INTO t(tag_id, tag)
VALUES (_tag_id, _tag)
RETURNING t.tag_id, t.tag
INTO _tag_id_, _tag_;
EXCEPTION WHEN UNIQUE_VIOLATION THEN
-- catch exception, return NULL
END
$func$ LANGUAGE plpgsql;
CREATE FUNCTION f_tag_id(_tag_id int, _tag text, OUT _tag_id_ int, OUT _tag_ text) AS
$func$
BEGIN
LOOP
SELECT t.tag_id, t.tag
FROM t
WHERE t.tag = _tag
UNION ALL
SELECT * -- !!!
FROM f_insert_tag(_tag_id, _tag)
LIMIT 1
INTO _tag_id_, _tag_;
EXIT WHEN _tag_id_ IS NOT NULL; -- else keep looping
END LOOP;
END
$func$ LANGUAGE plpgsql;
db<>fiddle here
For Postgres 9.5 or later:
CREATE FUNCTION f_tag_id(_tag_id int, _tag text, OUT _tag_id_ int, OUT _tag_ text) AS
$func$
BEGIN
LOOP
SELECT t.tag_id, t.tag
FROM t
WHERE t.tag = _tag
INTO _tag_id_, _tag_;
EXIT WHEN FOUND;
INSERT INTO t (tag_id, tag)
VALUES (_tag_id, _tag)
ON CONFLICT (tag) DO NOTHING
RETURNING t.tag_id, t.tag
INTO _tag_id_, _tag_;
EXIT WHEN FOUND;
END LOOP;
END
$func$ LANGUAGE plpgsql;
db<>fiddle here
Basics here:
Is SELECT or INSERT in a function prone to race conditions?

Pass array of tags to a plpgsql function and use it in WHERE condition

I'd like to create a function that returns items based on their tags. However, I do not know how to format an array in the IN() clause. I believe that is why I get no result.
Here is what I got:
CREATE OR REPLACE FUNCTION getItemsByTag(tags text[])
RETURNS TABLE (id bigint, title text, tag text[]) AS $$
BEGIN
IF array_length(tags, 1) > 0
THEN
EXECUTE format('
SELECT d.id, d.title, array_agg(t.title)
FROM items d
INNER JOIN item_tags dt
ON dt.item_id = d.id
INNER JOIN tags t
ON t.id = dt.tag_id
AND t.title IN (%L)
GROUP BY d.id, d.title
', array_to_string(tags, ','));
-- ELSE ...
END IF;
END;
$$ LANGUAGE plpgsql;
Then when I call:
select getItemsByTag('{"gaming", "sport"}');
I get no result even though there are items tagged with "gaming".
Test case
CREATE TABLE items(
id serial primary key,
title text);
CREATE TABLE tags(
id serial primary key,
title text);
CREATE TABLE item_tags(
item_id int references items(id),
tag_id int references tags(id),
primary key(item_id, tag_id));
insert into items (title) values ('my title 1'), ('my title 2');
insert into tags (title) values ('tag1'), ('tag2');
insert into item_tags (item_id, tag_id) values (1,1), (1, 2);
Function:
CREATE OR REPLACE FUNCTION getItemsByTag(tags text[])
RETURNS TABLE (id bigint, title text, tag text[]) AS $$
BEGIN
IF array_length(tags, 1) > 0
THEN
EXECUTE format('
SELECT d.id, d.title, array_agg(t.title)
FROM items d
INNER JOIN item_tags dt
ON dt.item_id = d.id
INNER JOIN tags t
ON t.id = dt.tag_id
AND t.title IN (%L)
GROUP BY d.id, d.title
', array_to_string(tags, ','));
-- ELSE ...
END IF;
END;
$$ LANGUAGE plpgsql;
Call:
select getItemsByTag('{"tag1", "tag2"}');
You are not actually returning the result. You would use RETURN QUERY EXECUTE for that. Example:
PostgreSQL parameterized Order By / Limit in table function
But you don't need dynamic SQL here to begin with ...
CREATE OR REPLACE FUNCTION get_items_by_tag(VARIADIC tags text[])
RETURNS TABLE (id int, title text, tag text[]) AS
$func$
BEGIN
IF array_length(tags, 1) > 0 THEN
-- NO need for EXECUTE
RETURN QUERY
SELECT d.id, d.title, array_agg(t.title)
FROM items d
JOIN item_tags dt ON dt.item_id = d.id
JOIN tags t ON t.id = dt.tag_id
AND t.title = ANY ($1) -- use ANY construct
GROUP BY d.id; -- PK covers whole table
-- array_to_string(tags, ',') -- no need to convert array with ANY
-- ELSE ...
END IF;
END
$func$ LANGUAGE plpgsql;
Call with actual array:
SELECT * FROM get_items_by_tag(VARIADIC '{tag1,tag2}'::text[]);
Or call with list of items ("dictionary"):
SELECT * FROM get_items_by_tag('tag1', 'tag2');
Major points
Use RETURN QUERY to actually return resulting rows.
PostgreSQL function returning multiple result sets
Don't use dynamic SQL unless you need it. (No EXECUTE here.)
Use an ANY construct instead of IN. Why?
How to use ANY instead of IN in a WHERE clause with Rails?
I suggest a VARIADIC function for convenience. This way you can either pass an array or a list of items at your choosing. See:
Pass multiple values in single parameter
Avoid mixed-case identifiers in Postgres if possible.
Are PostgreSQL column names case-sensitive?
Not sure why you have IF array_length(tags, 1) > 0 THEN, but can probably be replaced with IF tags IS NOT NULL THEN or no IF at all and follow up with IF NOT FOUND THEN. More:
Dynamic SQL (EXECUTE) as condition for IF statement
Try to use in place of tags in format statement this:
'''' || array_to_string(tags, "','") || '''' the result in the IN clause will be like IN ('gaming','sport').
It's because I'm not returning anything.
return query EXECUTE format('
SELECT d.id, d.title, array_agg(t.title)
FROM items d
INNER JOIN item_tags dt
ON dt.item_id = d.id
INNER JOIN tags t
ON t.id = dt.tag_id
AND t.title = ANY(%L)
GROUP BY d.id, d.title
', tags) ;

Plpgsql : non recursive category tree function doesn't return any rows :(

So, here's the function that would return the products of a given category and its child categories. Its a 3 level tree. The function is fine, but when i run it, it says 0 rows returned. Any ideas?
EDIT: parents1 and parents2 are supposed to be arrays of the children of the parent category. Parents1 children of $1 , and parents2 children of all parents1 nodes.
CREATE OR REPLACE FUNCTION ecommerce.select_products_by_category(par bigint)
RETURNS SETOF ecommerce.product AS
$BODY$
declare
result ecommerce.product;
parents bigint[];
parents2 bigint[];
i int;
begin
parents := array(
select category_id from ecommerce.category where parent_id = par
);
return query select * from ecommerce.product where category_id = par;
for i in 1..array_upper(parents,1)
loop
return query select * from ecommerce.product where category_id = parents[i];
raise notice 'p %',parents[i];
end loop;
for i in 1..array_upper(parents,1)
loop
parents2 := array(
select category_id from ecommerce.category where parent_id = parents[i]
);
end loop;
for i in 1..array_upper(parents2,1)
loop
return query select * from ecommerce.product where category_id = parents2[i];
raise notice 'p2 %',parents2[i];
end loop;
--return query theset;
end ; $BODY$
and this is how i run it
SELECT * From ecommerce.select_products_by_category(
1
);
Your code cannot to work. The result of table function is related with any individual CALL of table function, not with global CALL of table function. Any table returning recursive function have to have use a pattern:
CREATE OR REPLACE FUNCTION foo(_parent_id integer)
RETURNS TABLE (node_id integer, node_val, parent_id integer) AS $$
BEGIN
FOR node_id, node_val, parent_id IN
SELECT f.node_id, f.node_val, f.parent_id
FROM footab f
WHERE f.parent_id = _parent_id
LOOP
RETURN NEXT;
/*
* Copy result of recursive call to function result
*/
RETURN QUERY SELECT * FROM foo(node_id);
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
When you use CTE, then then you can get result little bit faster and the code will be more readable:
WITH RECURSIVE t AS (
SELECT node_id, node_val, parent_id FROM footab
WHERE parent_id = <<root_id>>
UNION ALL
SELECT node_id, node_val, parent_id FROM footab, t
WHERE footab.parent_id = t.id
) SELECT * FROM t;

Return row from upsert method

I have an upsert function that I modified from the documentation. However I have been trying to return the updated or inserted row. I'm calling this function from a node application and I need to keep track of which record has either been updated or inserted especially during sync script.
Here is the function:
create or replace function upsert_test(d TEXT, sys INT, val INT, p INT, inter BOOLEAN)
returns void as $$
begin
update test_table set description=d, code=sys, val_id=val, provider_id=p, connect=inter where code=sys and val_id=val and provider_id=p;
if found then
return;
end if;
begin
insert into test_table (description, code, val_id, provider_id, connect) values (d, sys, val, p, inter);
return;
exception when unique_violation then
end;
return;
end;
$$ language plpgsql;
I have tried to change the return type and have the function return a record but I can't seem to get it working.
Use the RETURNING clause. You can combine it with RETURN QUERY ...
CREATE OR REPLACE FUNCTION upsert_t2(d text, sys int, val int, p int, inter bool)
RETURNS SETOF test_table AS
$func$
BEGIN
RETURN QUERY
UPDATE test_table t
SET description = d
,code = sys
,val_id = val
,provider_id = p
,connect = inter
WHERE t.code = sys
AND t.val_id = val
AND t.provider_id = p
RETURNING t.*;
IF FOUND THEN
RETURN;
END IF;
BEGIN
RETURN QUERY
INSERT INTO test_table (description, code, val_id, provider_id, connect)
VALUES (d, sys, val, p, inter)
RETURNING *;
EXCEPTION WHEN UNIQUE_VIOLATION THEN
END;
RETURN;
END
$func$ LANGUAGE plpgsql;
Call:
SELECT * FROM upsert_t2(...)
Reply to comment
I would try to avoid updates completely that do not change anything. Also, I would look to a data-modifying CTE in a loop:
CREATE OR REPLACE FUNCTION upsert_cte(d text, sys int, val int, p int
, inter bool)
RETURNS SETOF test_table AS
$func$
BEGIN
LOOP
BEGIN
RETURN QUERY
WITH sel AS (
SELECT t.pk_col -- primary key column
FROM test_table t
WHERE t.code = sys
AND t.val_id = val
AND t.provider_id = p
FOR SHARE -- lock
)
, ins AS (
INSERT INTO test_table (description, code, val_id, provider_id, connect)
SELECT d, sys, val, p, inter
WHERE NOT EXISTS (SELECT 1 FROM sel) -- if not found
RETURNING *
)
, upd AS (
UPDATE test_table t
SET description = d
,code = sys
,val_id = val
,provider_id = p
,connect = inter
FROM sel
WHERE sel.pk_col = t.pk_col -- if found (possibly mult. rows)
AND t.description IS DISTINCT FROM d
,t.code IS DISTINCT FROM sys
,t.val_id IS DISTINCT FROM val
,t.provider_id IS DISTINCT FROM p
,t.connect IS DISTINCT FROM inter -- only if anything changes
RETURNING t.*
)
SELECT * FROM ins
UNION ALL
SELECT * FROM upd;
RETURN; -- No error occurred, exit loop
EXCEPTION WHEN UNIQUE_VIOLATION THEN -- inserted in concurrent session
RAISE NOTICE 'It happened!'; -- hardly ever happens, keep looping
END;
END LOOP;
END
$func$ LANGUAGE plpgsql;
Explanation and links in this related answer:
Is SELECT or INSERT in a function prone to race conditions?

Return multiple fields as a record in PostgreSQL with PL/pgSQL

I am writing a SP, using PL/pgSQL.
I want to return a record, comprised of fields from several different tables. Could look something like this:
CREATE OR REPLACE FUNCTION get_object_fields(name text)
RETURNS RECORD AS $$
BEGIN
-- fetch fields f1, f2 and f3 from table t1
-- fetch fields f4, f5 from table t2
-- fetch fields f6, f7 and f8 from table t3
-- return fields f1 ... f8 as a record
END
$$ language plpgsql;
How may I return the fields from different tables as fields in a single record?
[Edit]
I have realized that the example I gave above was slightly too simplistic. Some of the fields I need to be retrieving, will be saved as separate rows in the database table being queried, but I want to return them in the 'flattened' record structure.
The code below should help illustrate further:
CREATE TABLE user (id int, school_id int, name varchar(32));
CREATE TYPE my_type AS (
user1_id int,
user1_name varchar(32),
user2_id int,
user2_name varchar(32)
);
CREATE OR REPLACE FUNCTION get_two_users_from_school(schoolid int)
RETURNS my_type AS $$
DECLARE
result my_type;
temp_result user;
BEGIN
-- for purpose of this question assume 2 rows returned
SELECT id, name INTO temp_result FROM user where school_id = schoolid LIMIT 2;
-- Will the (pseudo)code below work?:
result.user1_id := temp_result[0].id ;
result.user1_name := temp_result[0].name ;
result.user2_id := temp_result[1].id ;
result.user2_name := temp_result[1].name ;
return result ;
END
$$ language plpgsql
Don't use CREATE TYPE to return a polymorphic result. Use and abuse the RECORD type instead. Check it out:
CREATE FUNCTION test_ret(a TEXT, b TEXT) RETURNS RECORD AS $$
DECLARE
ret RECORD;
BEGIN
-- Arbitrary expression to change the first parameter
IF LENGTH(a) < LENGTH(b) THEN
SELECT TRUE, a || b, 'a shorter than b' INTO ret;
ELSE
SELECT FALSE, b || a INTO ret;
END IF;
RETURN ret;
END;$$ LANGUAGE plpgsql;
Pay attention to the fact that it can optionally return two or three columns depending on the input.
test=> SELECT test_ret('foo','barbaz');
test_ret
----------------------------------
(t,foobarbaz,"a shorter than b")
(1 row)
test=> SELECT test_ret('barbaz','foo');
test_ret
----------------------------------
(f,foobarbaz)
(1 row)
This does wreak havoc on code, so do use a consistent number of columns, but it's ridiculously handy for returning optional error messages with the first parameter returning the success of the operation. Rewritten using a consistent number of columns:
CREATE FUNCTION test_ret(a TEXT, b TEXT) RETURNS RECORD AS $$
DECLARE
ret RECORD;
BEGIN
-- Note the CASTING being done for the 2nd and 3rd elements of the RECORD
IF LENGTH(a) < LENGTH(b) THEN
ret := (TRUE, (a || b)::TEXT, 'a shorter than b'::TEXT);
ELSE
ret := (FALSE, (b || a)::TEXT, NULL::TEXT);
END IF;
RETURN ret;
END;$$ LANGUAGE plpgsql;
Almost to epic hotness:
test=> SELECT test_ret('foobar','bar');
test_ret
----------------
(f,barfoobar,)
(1 row)
test=> SELECT test_ret('foo','barbaz');
test_ret
----------------------------------
(t,foobarbaz,"a shorter than b")
(1 row)
But how do you split that out in to multiple rows so that your ORM layer of choice can convert the values in to your language of choice's native data types? The hotness:
test=> SELECT a, b, c FROM test_ret('foo','barbaz') AS (a BOOL, b TEXT, c TEXT);
a | b | c
---+-----------+------------------
t | foobarbaz | a shorter than b
(1 row)
test=> SELECT a, b, c FROM test_ret('foobar','bar') AS (a BOOL, b TEXT, c TEXT);
a | b | c
---+-----------+---
f | barfoobar |
(1 row)
This is one of the coolest and most underused features in PostgreSQL. Please spread the word.
You need to define a new type and define your function to return that type.
CREATE TYPE my_type AS (f1 varchar(10), f2 varchar(10) /* , ... */ );
CREATE OR REPLACE FUNCTION get_object_fields(name text)
RETURNS my_type
AS
$$
DECLARE
result_record my_type;
BEGIN
SELECT f1, f2, f3
INTO result_record.f1, result_record.f2, result_record.f3
FROM table1
WHERE pk_col = 42;
SELECT f3
INTO result_record.f3
FROM table2
WHERE pk_col = 24;
RETURN result_record;
END
$$ LANGUAGE plpgsql;
If you want to return more than one record you need to define the function as returns setof my_type
Update
Another option is to use RETURNS TABLE() instead of creating a TYPE which was introduced in Postgres 8.4
CREATE OR REPLACE FUNCTION get_object_fields(name text)
RETURNS TABLE (f1 varchar(10), f2 varchar(10) /* , ... */ )
...
To return a single row
Simpler with OUT parameters:
CREATE OR REPLACE FUNCTION get_object_fields(_school_id int
, OUT user1_id int
, OUT user1_name varchar(32)
, OUT user2_id int
, OUT user2_name varchar(32)) AS
$func$
BEGIN
SELECT INTO user1_id, user1_name
u.id, u.name
FROM users u
WHERE u.school_id = _school_id
LIMIT 1; -- make sure query returns 1 row - better in a more deterministic way?
user2_id := user1_id + 1; -- some calculation
SELECT INTO user2_name
u.name
FROM users u
WHERE u.id = user2_id;
END
$func$ LANGUAGE plpgsql;
Call:
SELECT * FROM get_object_fields(1);
You don't need to create a type just for the sake of this plpgsql function. It may be useful if you want to bind multiple functions to the same composite type. Else, OUT parameters do the job.
There is no RETURN statement. OUT parameters are returned automatically with this form that returns a single row. RETURN is optional.
Since OUT parameters are visible everywhere inside the function body (and can be used just like any other variable), make sure to table-qualify columns of the same name to avoid naming conflicts! (Better yet, use distinct names to begin with.)
Simpler yet - also to return 0-n rows
Typically, this can be simpler and faster if queries in the function body can be combined. And you can use RETURNS TABLE() (since Postgres 8.4, long before the question was asked) to return 0-n rows.
The example from above can be written as:
CREATE OR REPLACE FUNCTION get_object_fields2(_school_id int)
RETURNS TABLE (user1_id int
, user1_name varchar(32)
, user2_id int
, user2_name varchar(32)) AS
$func$
BEGIN
RETURN QUERY
SELECT u1.id, u1.name, u2.id, u2.name
FROM users u1
JOIN users u2 ON u2.id = u1.id + 1
WHERE u1.school_id = _school_id
LIMIT 1; -- may be optional
END
$func$ LANGUAGE plpgsql;
Call:
SELECT * FROM get_object_fields2(1);
RETURNS TABLE is effectively the same as having a bunch of OUT parameters combined with RETURNS SETOF record, just shorter.
The major difference: this function can return 0, 1 or many rows, while the first version always returns 1 row.
Add LIMIT 1 like demonstrated to only allow 0 or 1 row.
RETURN QUERY is simple way to return results from a query directly.
You can use multiple instances in a single function to add more rows to the output.
db<>fiddle here (demonstrating both)
Varying row-type
If your function is supposed to dynamically return results with a different row-type depending on the input, read more here:
Refactor a PL/pgSQL function to return the output of various SELECT queries
If you have a table with this exact record layout, use its name as a type, otherwise you will have to declare the type explicitly:
CREATE OR REPLACE FUNCTION get_object_fields
(
name text
)
RETURNS mytable
AS
$$
DECLARE f1 INT;
DECLARE f2 INT;
…
DECLARE f8 INT;
DECLARE retval mytable;
BEGIN
-- fetch fields f1, f2 and f3 from table t1
-- fetch fields f4, f5 from table t2
-- fetch fields f6, f7 and f8 from table t3
retval := (f1, f2, …, f8);
RETURN retval;
END
$$ language plpgsql;
You can achieve this by using simply as a returns set of records using return query.
CREATE OR REPLACE FUNCTION schemaName.get_two_users_from_school(schoolid bigint)
RETURNS SETOF record
LANGUAGE plpgsql
AS $function$
begin
return query
SELECT id, name FROM schemaName.user where school_id = schoolid;
end;
$function$
And call this function as : select * from schemaName.get_two_users_from_school(schoolid) as x(a bigint, b varchar);
you can do this using OUT parameter and CROSS JOIN
CREATE OR REPLACE FUNCTION get_object_fields(my_name text, OUT f1 text, OUT f2 text)
AS $$
SELECT t1.name, t2.name
FROM table1 t1
CROSS JOIN table2 t2
WHERE t1.name = my_name AND t2.name = my_name;
$$ LANGUAGE SQL;
then use it as a table:
select get_object_fields( 'Pending') ;
get_object_fields
-------------------
(Pending,code)
(1 row)
or
select * from get_object_fields( 'Pending');
f1 | f
---------+---------
Pending | code
(1 row)
or
select (get_object_fields( 'Pending')).f1;
f1
---------
Pending
(1 row)
CREATE TABLE users(user_id int, school_id int, name text);
insert into users values (1, 10,'alice')
,(5, 10,'boy')
,(13, 10,'cassey')
,(17, 10,'delores')
,(4, 11,'elaine');
I setted the user_id as arbitrary int. The function input parameter is the school_id. So if the school_id is 10 you hope to get the following result:
user_id | name | user_id | name
---------+-------+---------+------
1 | alice | 5 | boy
So your query should be something like:
with a as (
select u1.user_id,
u1.name from users u1
where school_id = 10 order by user_id limit 1),
b as
(select u2.user_id,u2.name from users u2
where school_id = 10 order by user_id limit 1 offset 1 )
select * from a cross JOIN b ;
So let's wrap the query to the plpgsql function.
CREATE OR REPLACE FUNCTION
get_object_fields2(_school_id int)
RETURNS TABLE (user1_id int
, user1_name text
, user2_id int
, user2_name text)
LANGUAGE plpgsql AS
$func$
DECLARE countu integer;
BEGIN
countu := (
select count(*) from users where school_id = _school_id);
IF countu >= 2 THEN
RETURN QUERY
with a as (
select u1.user_id,
u1.name from users u1
where school_id = _school_id
order by user_id limit 1),
b as(
select u2.user_id,u2.name from users u2
where school_id = _school_id
order by user_id limit 1 offset 1 )
select * from a cross JOIN b;
elseif countu = 1 then
return query
select u1.user_id, u1.name,u1.user_id, u1.name
from users u1 where school_id = _school_id;
else
RAISE EXCEPTION 'not found';
end if;
END
$func$;