Consider a table named
Triangle with the following structure:
The primary key for this table is
(x, y, z), each row of which represents the lengths of three line segments. Your task is to create an SQL query that can determine for each row if the three line segments can form a triangle.
Here's an example for better understanding:
In the example above, the first row cannot form a triangle because the sum of any two sides of a triangle should be greater than the third side, i.e.,
x + y > z,
x + z > y, and
y + z > x. However,
13 + 15 is not greater than
30, hence the 'No' in the 'triangle' column. In contrast, the lengths in the second row can form a triangle since
10 + 20 > 15,
10 + 15 > 20, and
20 + 15 > 10.
Here's a simple yet effective SQL query that leverages the concept of conditional logic (
CASE...WHEN...THEN...ELSE) to determine if three lengths can form a triangle:
SELECT x, y, z, CASE WHEN x + y > z AND x + z > y AND y + z > x THEN 'Yes' ELSE 'No' END AS 'triangle' FROM Triangle
This query will output 'Yes' if the lengths can form a triangle, and 'No' otherwise. The beauty of this query lies in its simplicity and directness. It directly applies the triangle inequality theorem, which states that the sum of the lengths of any two sides of a triangle is greater than the length of the remaining side.
Interestingly, the same query had different execution times on two different submissions:
- First submission: runtime 624ms, beating 18.82% of other SQL submissions.
- Second submission: runtime 396ms, beating 83.20% of other SQL submissions.
This difference can be attributed to several factors including server load and performance at the time of query execution.
You can find the original problem at LeetCode.
Want to see more insightful solutions and tech-related content? Feel free to connect with me on my Beacons page.