1

How can I check if the first query returns data, and if yes return this data or search in another table? Something like:

CREATE OR REPLACE FUNCTION finddata() RETURNS TABLE (content text) AS $$
BEGIN
  # now pseudocode
  x = SELECT foo FROM bar WHERE ....;
  if num_rows(x) > 0
    return x
  else
    RETURN QUERY SELECT foo FROM bar2 WHERE ....;
END;
$$ LANGUAGE plpgsql;

Thanks Klaus

2
  • Do you want to know if it's query1 or query2, or you just want the results from both ? If you want the results you can do an union or a join with some CASE/WHEN in the select. No need of procedure then. Commented Feb 21, 2019 at 10:37
  • I do not want a union. The function should return the data either from table bar, or if not found in bar, then from table bar2. Commented Feb 21, 2019 at 10:40

2 Answers 2

2

You can do it in easier way without checking if data exists - I already use this construct in more functions with success (function does not end after first RETURN QUERY - you can have several of them in sequence in function as far as they all return the same structure - I also use it when necessary):

CREATE OR REPLACE FUNCTION finddata() RETURNS TABLE (content text) AS $$
DECLARE
  cnt int;
BEGIN
  RETURN QUERY SELECT foo FROM bar WHERE ....;
  GET DIAGNOSTICS cnt = ROW_COUNT;
  if cnt = 0 then
    RETURN QUERY SELECT foo FROM bar2 WHERE ....;
  end if;
END;
$$ LANGUAGE plpgsql;
Sign up to request clarification or add additional context in comments.

Comments

0

use IF EXISTS

CREATE OR REPLACE FUNCTION finddata() 
RETURNS TABLE (content text) AS $$
  BEGIN
  IF EXISTS ( SELECT foo FROM bar WHERE .... )
   THEN
    return QUERY SELECT foo FROM bar;
  else
    RETURN QUERY SELECT foo FROM bar2 WHERE ....;
END;
$$ LANGUAGE plpgsql;

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.