简体   繁体   中英

how to optimize pl sql if statement with multiple OR conditions

I'm new to pl sql can you please let me know how i can optimize the below if statement?

IF (inSeries=‘90’) OR (inSeries=‘91’) OR (inSeries=‘92’) OR (inSeries=‘93’) OR (inSeries=‘94’) THEN

like in sql we can use

WHERE inSeries IN (‘90’,’91’,’92’,’93’,’94’)

In PLSQL also 'IN' condition works as IF condition

declare
inSeries varchar2(2) := '90';
begin
if inseries in ('90','91','92','93','94')
then
dbms_output.put_line(inseries ||':this is within series');
else
dbms_output.put_line(inseries ||':this is out of series');
end if;
end;

-- output
90:this is within series
80:this is out of series

but there is another way depending on the business logic, as i can see from your question that its in series increment, you can directly use greater than and less than combination...

Optimizer will most probably rewrite query so your IN will become OR anyway. Compare line 3 in the query and the very last line:

SQL> select job
  2  from emp
  3  where deptno in (10, 20, 30, 40);

JOB
---------
CLERK
SALESMAN
<snip>

14 rows selected.


Execution Plan
----------------------------------------------------------
Plan hash value: 3956160932

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |    14 |   154 |     3   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL| EMP  |    14 |   154 |     3   (0)| 00:00:01 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("DEPTNO"=10 OR "DEPTNO"=20 OR "DEPTNO"=30 OR "DEPTNO"=40)

SQL>

您可以将SQL查询本身与“ EXISTS”关键字一起使用。

IF EXISTS (SELECT * FROM <table_name> WHERE inSeries IN (‘90’,’91’,’92’,’93’,’94’))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM