PL/SQL – Operators Precedence

  • Post author:
  • Post category:PL/SQL
  • Post comments:1 Comment

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

The precedence of operators goes as follows: =, <, >, <=, >=, <>, !=, ~=, ^=, IS NULL, LIKE, BETWEEN, IN.

OperatorOperation
**exponentiation
+, –identity, negation
*, /multiplication, division
+, -, ||addition, subtraction, concatenation
comparison
NOTlogical negation
ANDconjunction
ORinclusion

Example

Try the following example to understand the operator precedence available in PL/SQL −

DECLARE 
   a number(2) := 20; 
   b number(2) := 10; 
   c number(2) := 15; 
   d number(2) := 5; 
   e number(2) ; 
BEGIN 
   e := (a + b) * c / d;      -- ( 30 * 15 ) / 5 
   dbms_output.put_line('Value of (a + b) * c / d is : '|| e );  
   e := ((a + b) * c) / d;   -- (30 * 15 ) / 5 
   dbms_output.put_line('Value of ((a + b) * c) / d is  : ' ||  e );  
   e := (a + b) * (c / d);   -- (30) * (15/5) 
   dbms_output.put_line('Value of (a + b) * (c / d) is  : '||  e );  
   e := a + (b * c) / d;     --  20 + (150/5) 
   dbms_output.put_line('Value of a + (b * c) / d is  : ' ||  e ); 
END; 
/

When the above code is executed at the SQL prompt, it produces the following result −

Value of (a + b) * c / d is : 90 
Value of ((a + b) * c) / d is  : 90 
Value of (a + b) * (c / d) is  : 90 
Value of a + (b * c) / d is  : 50  
 
PL/SQL procedure successfully completed. 

This Post Has One Comment

Leave a Reply