SQL – Types of Triangle

Write a query identifying the type of each record in the TRIANGLES table using its three side lengths. Output one of the following statements for each record in the table:

  • Equilateral: It’s a triangle with  sides of equal length.
  • Isosceles: It’s a triangle with  sides of equal length.
  • Scalene: It’s a triangle with  sides of differing lengths.
  • Not A Triangle: The given values of AB, and C don’t form a triangle.

Input Format

The TRIANGLES table is described as follows:

Each row in the table denotes the lengths of each of a triangle’s three sides.

Sample Input

Sample Output

Isosceles 
Equilateral 
Scalene 
Not A Triangle

Solution

  1. Conditions for a triangle with A, B, C sides will be A+B>C, A+C>B, B+C>A
  2. Conditions for equilateral triangle is when A=B and B=C
  3. Conditions for isosceles triangle is either A=B or B=C or A=C
  4. If not 2 and 3 then scalene

MySQL

SELECT IF(A+B>C AND A+C>B AND B+C>A, 
       IF(A=B AND B=C, 'Equilateral', 
       IF(A=B OR B=C OR A=C, 'Isosceles', 
       'Scalene')), 
       'Not A Triangle') 
FROM TRIANGLES;

 

Oracle

SELECT 
    CASE  
        WHEN NOT ((a+b>c) AND (a+c>b) AND (b+c>a)) THEN 'Not A Triangle'
        WHEN a = b AND b = c THEN 'Equilateral'
        WHEN a = b OR b = c OR c = a THEN 'Isosceles'
        ELSE 'Scalene'
    END AS result
FROM triangles;

Source – Hackerrank