Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PL/SQL select into - if data exists

Tags:

plsql

I need to select into a local variable only if there exists data.

SELECT column1 INTO local_variable FROM table1 where column2 = <condition>;

Here if there is no data matching the condition I get a no data found error.

I need to select into the local variable only if there is some data matching the condition. Is there a simple query that will solve my problem.

like image 683
Avinash Avatar asked Sep 06 '11 07:09

Avinash


People also ask

How do you check if data exists in a table in Oracle?

Type a short Oracle program, using the following code as a guide: DECLARE record_exists INTEGER; BEGIN SELECT COUNT(*) INTO record_exists FROM your_table WHERE search_field = 'search value' AND ROWNUM = 1; IF record_exists = 1 THEN DBMS_OUTPUT. put_line('Record Exists') ELSE DBMS_OUTPUT.

Can we use if exists in Oracle?

The Oracle EXISTS condition is used in combination with a subquery and is considered "to be met" if the subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Can we use subquery in if statement in Oracle?

You cannot include SQL inside an IF statement.

Can we use simple SELECT query in PL SQL?

You can make the use of the SELECT INTO statement in PL/ SQL to retrieve the row containing single or multiple column values in the resultant for storing them in variables.


2 Answers

Probably the best way is to handle no_data_found

begin
  SELECT column1 INTO local_variable 
  FROM table1 where column2 = p_val;
exception
  when no_data_found then
    local_variable := null;
end;

Also, if you are selecting with primary key /unique key (that is column2 is unique) then there is a trick you can do

SELECT max(column1) INTO local_variable 
  FROM table1 where column2 = p_val;
like image 156
bpgergo Avatar answered Oct 07 '22 01:10

bpgergo


Well…do a count before doing the select. Or just handle the no_data_found exception.

You can open a cursor and fetch the rows, do a count and if it is greater than 0 then do your stuff with that record 😉

like image 35
André Fonseca Avatar answered Oct 07 '22 03:10

André Fonseca