2

I want to write a function to delete old rows in table Offers and then return the deleted rows.

CREATE OR REPLACE FUNCTION delOldOffers() RETURNS void AS $$
DELETE FROM "public"."Offers"
 WHERE created_at < now() - interval '7 days'

$$ LANGUAGE sql STABLE;

I wrote the above function but I am not sure how I can return rows that where deleted? If anyone can help that would be really great!

1 Answer 1

4

You need to declare your function to return a table (or setof) and use the returning clause:

CREATE OR REPLACE FUNCTION deloldoffers(p_num_days integer) 
  RETURNS setof offers 
AS $$
  DELETE FROM Offers
  WHERE created_at < current_timestamp - make_interval(days => p_num_days)
  returning *;
$$ LANGUAGE sql;

To use it, you need to select "from" it:

select *
from deloldoffers(10);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the help! Can I do something similar for update also to get the updated rows back - CREATE OR REPLACE FUNCTION updateOldoffers(p_num_days integer) RETURNS setof offers AS $$ UPDATE "public"."Offers" SET active = 'false' WHERE created_at < current_timestamp - make_interval(days => p_num_days) returning *; $$ LANGUAGE 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.