Triangle Judgement - Problem

You have a table Triangle containing the lengths of three line segments.

Write an SQL query to report for every three line segments whether they can form a triangle.

A triangle can be formed if the sum of any two sides is greater than the third side. This must be true for all three combinations:

  • x + y > z
  • x + z > y
  • y + z > x

Return the result table in any order.

Table Schema

Triangle
Column Name Type Description
x PK int Length of first line segment
y PK int Length of second line segment
z PK int Length of third line segment
Primary Key: (x, y, z)
Note: Each row contains the lengths of three line segments that need to be tested for triangle formation

Input & Output

Example 1 — Basic Triangle Test
Input Table:
x y z
13 15 30
10 20 15
Output:
x y z triangle
13 15 30 No
10 20 15 Yes
💡 Note:

For the first row: 13 + 15 = 28, which is not greater than 30, so it cannot form a triangle.

For the second row: 10 + 20 = 30 > 15, 10 + 15 = 25 > 20, and 20 + 15 = 35 > 10. All conditions are satisfied, so it can form a triangle.

Example 2 — Edge Cases
Input Table:
x y z
1 1 1
1 2 3
Output:
x y z triangle
1 1 1 Yes
1 2 3 No
💡 Note:

For equilateral triangle (1,1,1): All sides equal, so 1+1=2 > 1 for all combinations - forms a triangle.

For degenerate case (1,2,3): 1+2=3 which equals the third side, not greater than it - cannot form a triangle.

Constraints

  • 1 ≤ x, y, z ≤ 100
  • All side lengths are positive integers

Visualization

Tap to expand
Triangle Judgement ProblemInput DataTriangle Tablex=13, y=15, z=30x=10, y=20, z=15Triangle TestInequality Check13+15=28 ≤ 30 ✗10+20=30 > 15 ✓10+15=25 > 20 ✓20+15=35 > 10 ✓Output ResultTriangle ColumnNoYesTriangle Inequality TheoremFor sides a, b, c to form a triangle:a + b > c AND a + c > b AND b + c > a
Understanding the Visualization
1
Input
Three line segment lengths
2
Check
Apply triangle inequality theorem
3
Result
Yes if triangle, No otherwise
Key Takeaway
🎯 Key Insight: Use CASE WHEN with triangle inequality conditions to validate geometric constraints in SQL
Asked in
Amazon 15 Microsoft 12
28.5K Views
Medium Frequency
~8 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen