1

I have table with multiple duplicates and I want to make from these a function. Could you please help me to make a function from this code? thanks.

SELECT id_member,id_service,amount,date, count(*) as number_of_duplicates
from evidence
GROUP BY id_member,id_service,amount,date
HAVING COUNT(*) > 1;


CREATE OR REPLACE FUNCTION check_for_duplicates()
RETURNS VOID AS
$BODY$
BEGIN
SELECT id_member,id_service,amount,date, count(*) as number_of_duplicates
from evidence
GROUP BY id_member,id_service,amount,date
HAVING COUNT(*) > 1;
END;
$BODY$
LANGUAGE ‘plpgsql‘;
3
  • So you want your function to simply return that result? Commented Jan 29, 2018 at 12:54
  • Yes. I have trouble with creating function from these peace of code. Commented Jan 29, 2018 at 12:57
  • I think its because you return VOID and have no out parameter - try returning a table instead?.. although I don't understand why you want to wrap it up to plpgsql - no arguments, no variables... Commented Jan 29, 2018 at 13:00

1 Answer 1

2

If a function should return a result set it needs to be declared as returns table () or returns setof

You also don't need a PL/pgSQL function for that, a simple SQL function will do and is more efficient:

CREATE OR REPLACE FUNCTION check_for_duplicates()
RETURNS table (id_member integer, id_service integer, amount numeric, date date, number_of_duplicates bigint) 
$BODY$
  SELECT id_member,id_service,amount,date, count(*) as number_of_duplicates
  from evidence
  GROUP BY id_member,id_service,amount,date
  HAVING COUNT(*) > 1;
$BODY$
LANGUAGE sql;

You didn't show us the definition of the table evidence so I had to guess the data type of the columns. You will need to adjust the types in the returns table (...) part to match the types from the table.

Having said that: I would create a view for things like that, not a function.


Unrelated, but: date is a horrible name for a column. For one because it's also a keyword but more importantly it doesn't document what the column contains: a release date? An expiration date? A due date?

Sign up to request clarification or add additional context in comments.

Comments

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.