2

I need to write oracle query (Just query) to select values from table, and if not found select from another table.

any help to do this in pl/sql?

2
  • Are you looking for a PL/SQL function or just a plain SQL statement? How different are the two queries hinging on the data existence test? Is it a single column, or many different ones? Commented Mar 13, 2014 at 13:29
  • pl/sql query, and it return many columns Commented Mar 13, 2014 at 13:29

3 Answers 3

2

SELECT * FROM firstTable

UNION ALL

SELECT * FROM secondTable WHERE (SELECT count(*) FROM FIRST_TABLE ) = 0

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

Comments

0

You can enclose the SELECT statement within a block and add an exception handler to it.

So, if there are no rows selected from the first table, then you select from the second table. The structure would be something like below:

Begin
    select <many columns> into <many variables or row type>
    From Table1
    where <conditions>;
EXCEPTION
    WHEN NO_DATA_FOUND THEN

    select <many columns> into <many variables or row type>
    From Table2
    Where <Conditions>;
End;

References:

Another related SO question

Exception Handlers

Documentation for the SELECT INTO statement

Comments

0

Here is an example of a PL/SQL function that will perform a test, and then execute a secondary query based upon the results of the test. You can adjust it to fit your needs:

set serveroutput on;

declare
  row_count number;
  column1 varchar(10);
  column2 varchar(10);
  column3 number;

begin

  /*Perform your test*/
  select count(target_column) into row_count
  from my_table
  where condition_column = 'x';

  /*Run your secondary query based on the output of the first*/
  if row_count > 0 then
    select 
      col_x into column1,
      col_y into column2,
      col_z into column3
    from my_other_table_A;
  else
    select 
      col_a into column1,
      col_b into column2,
      col_c into column3
    from my_other_table_B;
  end if;

  /*Show the results*/
  dbms_output.put_line('column1: ' || column1);
  dbms_output.put_line('column2: ' || column2);
  dbms_output.put_line('column3: ' || column3);

end;
/

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.