Skip to content
Advertisement

SQL query to classify triangles into Equilateral, Isosceles, etc

Please tell me what is wrong in this code? I’m getting “ERROR at line 2: ORA-00907: missing right parenthesis” for the following snippet. Please help me out.

select (
IF (A = B or B = C or C = A) THEN
DBMS_OUTPUT.PUT_LINE('Isosceles')
ELSIF (A=B and B=c) THEN
DBMS_OUTPUT.PUT_LINE('Equilateral')
ELSIF (A != B) and (B != C) and (A+B>C or B+C>A or A+C>B)THEN
DBMS_OUTPUT.PUT_LINE('Scalene')
ELSE
DBMS_OUTPUT.PUT_LINE('Not A Triangle')
END IF
)
from triangles;

Advertisement

Answer

Keep in mind that CASE statements are evaluated IN ORDER – the first WHEN clause that fits “wins” and no further evaluation is made. So:

with
     triangles ( A, B, C ) as (
       select 20, 20, 23 from dual union all
       select 20, 20, 20 from dual union all
       select 20, 21, 22 from dual union all
       select 13, 14, 30 from dual
     )
select A, B, C, 
       case
            when A+B <= C  or B+C <= A or C+A <= B then 'Not A Triangle'                
            when A    = B and B    = C             then 'Equilateral'
            when A    = B  or B    = C or A    = C then 'Isosceles'
            else                                        'Scalene'  
            end  as classification
from   triangles
;

  A   B   C   CLASSIFICATION
--- --- ---   --------------
 20  20  23   Isosceles
 20  20  20   Equilateral
 20  21  22   Scalene
 13  14  30   Not A Triangle

4 rows selected.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement