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 3 sides of equal length.
- Isosceles: It’s a triangle with 2 sides of equal length.
- Scalene: It’s a triangle with 3 sides of differing lengths.
- Not A Triangle: The given values of A, B, and C don’t form a triangle.
Input Format
The TRIANGLES table is described as follows:
Column | Type |
---|---|
A | Integer |
B | Integer |
C | Integer |
Each row in the table denotes the lengths of each of a triangle’s three sides.
Sample Input
A | B | C |
---|---|---|
20 | 20 | 23 |
20 | 20 | 20 |
20 | 21 | 22 |
13 | 14 | 30 |
Sample Output
Isosceles
Equilateral
Scalene
Not A Triangle
Explanation
Values in the tuple (20, 20, 23) form an Isosceles triangle, because A=B.
Values in the tuple (20, 20, 20) form an Equilateral triangle, because A=B=C.
Values in the tuple (20, 21, 22) form a Scalene triangle, because A≠B≠C.
Values in the tuple (13, 14, 30) cannot form a triangle because the combined value
of sides A and B is not larger than that of side C.
To solve this query I am using MySQL CASE Function
The CASE function in MySQL allows you to perform conditional logic in a SQL statement. It checks a condition and returns a value if the condition is true or false. You can use it to check for multiple conditions and return different results based on those conditions. If none of the conditions are true, you can specify a default value to be returned.
Syntax:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN condition3 THEN resultN
ELSE result
END;
Solution :
SELECT
CASE
WHEN (A + B <= C) | (B + C <= A) | (A + C <= B) THEN 'Not A Triangle'
WHEN (A = B) & (B = C) THEN 'Equilateral'
WHEN ((A = B) & (A != C)) | ((B = C) & (B != A)) | ((A = C) & (A != B)) THEN 'Isosceles'
WHEN (A != B) & (B != C) & (A != C) THEN 'Scalene'
END AS Triangle_Type
FROM
TRIANGLES;
Output:
Equilateral
Equilateral
Isosceles
Equilateral
Isosceles
Equilateral
Scalene
Not A Triangle
Scalene
Scalene
Scalene
Not A Triangle
Explanation:
In the above query, we have used MySQL CASE Function. In the case statement, I have written the first condition with | (OR) Operator
if this statement is true then we will get “Not A Triangle” Output.
If the second condition is true then we will get an ‘Equilateral’ Output.
If the third condition is true then we will get ‘Isosceles’ Output.
If the fourth condition is true then we will get ‘Scalene’ Output.
if you are learning SQL then this site will help you a lot. I solve various SQL questions and explain them on this site. I am now solving SQL questions on HackerRank and writing explanations of Solutions on this site. I request you to share this site with your friends as well.
Read This –