Skip to content

Valid Triangle Check

Write a CASE expression that checks whether three side lengths form a valid triangle.

Builds on CASE Expressions

Stage 1intro11 min read

Assume the side lengths are positive. If the table does not guarantee that, check x > 0 AND y > 0 AND z > 0 before applying the triangle inequalities.


Problem Statement

A geometry software needs to check whether three given line segments can actually form a triangle.

Business context Before drawing or rendering a triangle in the software, the system first needs to confirm the three side lengths are geometrically valid. If they are not, the software should not attempt to draw it.

Goal For every set of three segment lengths, decide whether they can form a valid triangle or not.

Input A table with three columns representing the lengths of three line segments: x, y, and z.

Output The same three columns, plus one extra column called triangle, showing either Yes or No.


Table Structure

Table: Triangle

Column NameType
xint
yint
zint

Column Meaning

  • x — length of the first line segment
  • y — length of the second line segment
  • z — length of the third line segment

Important Notes

  • The combination (x, y, z) is the primary key, so no two rows are exact duplicates of each other.
  • All three columns are integers, so there is no need to worry about decimals or rounding.
  • The table does not mention NOT NULL, but in practice, side lengths are expected to always have a value. If a NULL ever appears, any comparison involving it will return UNKNOWN, which behaves like FALSE inside a CASE condition, and the row would fall through to the ELSE branch.
  • Order of x, y, z does not matter for the logic. A triangle is still a triangle no matter which side is called x, y, or z.

Example

Input: Triangle table

xyz
131530
102015

Expected Output

xyztriangle
131530No
102015Yes
Try it: Valid Triangle CheckTables: Triangle
Show the tables and sample rows
CREATE TABLE Triangle (x INTEGER, y INTEGER, z INTEGER);
INSERT INTO Triangle VALUES
  (13, 15, 30),
  (10, 20, 15);
Runs in your browser on SQLite, with common MySQL functions

Explanation

  • Row 1: 13 + 15 = 28, which is less than 30, so this fails the triangle rule. Not a valid triangle.
  • Row 2: 10 + 20 = 30 (greater than 15), 10 + 15 = 25 (greater than 20), 15 + 20 = 35 (greater than 10). All three checks pass, so this is a valid triangle.

Intuition

Think about three sticks lying on a table. Can you always join their ends together to form a triangle? Not always.

If one stick is way too long compared to the other two combined, the two shorter sticks simply cannot reach each other’s ends. Picture two short sticks, laid flat, trying to reach across a much longer third stick. They physically fall short. No triangle forms, you just get a flat, open shape.

This everyday idea is captured by a simple geometry rule called the triangle inequality theorem:

The sum of any two sides of a triangle must always be greater than the third side.

Since a triangle has three sides, this rule needs to be checked three times, once for each side being the “third side”:

  1. x + y > z
  2. x + z > y
  3. y + z > x

If even one of these three checks fails, the shape cannot close into a triangle. All three must pass at the same time.


Mental Model

Imagine you are testing a rubber band stretched around three pegs on a board, with the pegs placed at distances x, y, and z apart.

If any single side is too long compared to the sum of the other two, the rubber band cannot stretch far enough to reach around all three pegs and stay taut. It just goes slack or one side “gives up.”

Only when all three sides balance each other out (each one shorter than the combined length of the other two) does the rubber band form a proper closed triangle.

This mental picture is a nice way to remember why you need to check all three combinations, not just one.


Thought Process

Before jumping into SQL, think about this like a checklist problem, not a math problem.

Ask yourself:

  1. What is the actual condition that makes three lengths a valid triangle? (The triangle inequality theorem, checked three ways.)
  2. Do I need to compare rows to each other, or just look at one row at a time? Here, each row is independent. You only need the three values within that single row, nothing from other rows.
  3. Since this is a per-row decision with a Yes/No output, this is a strong signal for CASE, since CASE is exactly built to turn a condition into a labeled output.
  4. All three conditions must be true together, not just one of them. That means combining them with AND, not OR.

Once you see that this is “check three conditions per row, using AND, then label the result,” the SQL becomes very direct to write.


Approach

Step 1: Identify the rule The triangle inequality theorem must hold true in all three directions at once: x + y > z, x + z > y, and y + z > x.

Step 2: Combine the three checks Since all three conditions need to be true at the same time, join them using AND inside a single CASE condition.

Step 3: Assign the label If all three conditions pass, return 'Yes'. If even one fails, return 'No' using ELSE, since ELSE naturally catches every case where the WHEN condition is not fully true.

Step 4: Keep the original columns The output still needs to show x, y, and z alongside the new triangle column, so these are selected directly along with the CASE expression.


SQL Query

SELECT
    x,
    y,
    z,
    -- Check triangle inequality theorem in all three directions
    -- All three conditions must be true at once, so they are joined with AND
    CASE
        WHEN x + y > z AND x + z > y AND y + z > x THEN 'Yes'
        ELSE 'No'
    END AS triangle
FROM
    Triangle;

Query Explanation

  • SELECT x, y, z — brings back the original three side lengths unchanged, so the output still shows what the input was.
  • CASE WHEN … THEN … ELSE … END — this is the core logic. It checks a condition and returns one value if it is true, and a different value otherwise.
  • x + y > z AND x + z > y AND y + z > x — three separate comparisons, all combined using AND. Every single one must be TRUE for the whole condition to be TRUE. If even one comparison is FALSE, the entire AND expression becomes FALSE, and SQL moves to ELSE.
  • AS triangle — renames the CASE output column to triangle, matching the expected output format.
  • FROM Triangle — reads from the Triangle table, one row at a time. There is no WHERE, GROUP BY, or JOIN needed here, since each row is judged entirely on its own values.

Dry Run

Original table

xyz
131530
102015

↓

What SQL does first For each row, SQL evaluates the three comparisons inside the CASE condition.

↓

Row 1: x=13, y=15, z=30

CheckCalculationResult
x + y > z13 + 15 = 28 > 30FALSE
x + z > y13 + 30 = 43 > 15TRUE
y + z > x15 + 30 = 45 > 13TRUE

Since one check is FALSE, the AND condition overall is FALSE → result is No

↓

Row 2: x=10, y=20, z=15

CheckCalculationResult
x + y > z10 + 20 = 30 > 15TRUE
x + z > y10 + 15 = 25 > 20TRUE
y + z > x20 + 15 = 35 > 10TRUE

All three checks are TRUE → result is Yes

↓

Final output

xyztriangle
131530No
102015Yes

SQL Execution Flow

FROM Triangle
   ↓
Read one row at a time
   ↓
Evaluate CASE condition (three AND checks)
   ↓
Assign 'Yes' or 'No' based on result
   ↓
SELECT x, y, z, triangle
   ↓
Return final output

There is no WHERE, GROUP BY, HAVING, or ORDER BY in this query, so the execution flow stays simple. Each row is read once, evaluated once, and returned once.


Time Complexity

Time Complexity: O(n) The query scans every row exactly once and does a constant amount of work (three additions and three comparisons) per row. So the total work grows in a straight line with the number of rows, not faster.

Space Complexity: O(1) extra space, beyond the output itself. No temporary tables, no sorting, and no grouping are needed. The CASE expression is computed on the fly for each row and does not need to store anything extra in memory.

Why: Since each row is judged independently of every other row, there is no need to compare rows against each other, sort the data, or build any intermediate structure. This keeps both time and space usage minimal.


Common Mistakes to Avoid

Mistake 1: Using OR instead of AND

Why it happens: It feels natural to think “if any side breaks the rule, it fails,” which can lead to writing the conditions with OR by mistake.

Wrong:

CASE
    WHEN x + y > z OR x + z > y OR y + z > x THEN 'Yes'
    ELSE 'No'
END AS triangle

This is wrong because OR only needs one condition to be true, so almost every set of three positive numbers would incorrectly return Yes.

Correct:

CASE
    WHEN x + y > z AND x + z > y AND y + z > x THEN 'Yes'
    ELSE 'No'
END AS triangle

Mistake 2: Only checking one combination

Why it happens: Beginners sometimes assume checking just x + y > z is enough, forgetting a triangle has three sides, not one.

Wrong:

CASE
    WHEN x + y > z THEN 'Yes'
    ELSE 'No'
END AS triangle

This misses cases where x + y > z is true, but x + z is not greater than y, which still means no valid triangle.

Correct: Always check all three directions together, as shown in the main solution.

Mistake 3: Using >= instead of >

Why it happens: It can feel like “equal to” should count as valid, since the numbers look close.

Wrong:

WHEN x + y >= z AND x + z >= y AND y + z >= x THEN 'Yes'

If two sides add up to exactly the third side, the shape becomes a flat straight line, not a triangle. The theorem requires strictly greater than, not equal to.

Correct: Always use >, never >=, for triangle inequality checks.

Mistake 4: Forgetting to keep the original columns in the output

Why it happens: Focusing only on the new triangle column and forgetting the expected output also needs x, y, and z.

Wrong:

SELECT
    CASE WHEN x + y > z AND x + z > y AND y + z > x THEN 'Yes' ELSE 'No' END AS triangle
FROM Triangle;

Correct: Always SELECT x, y, z along with the CASE column, since the expected output includes all four columns.

Mistake 5: Not handling negative or zero values

Why it happens: The problem assumes valid positive lengths, but real data can sometimes contain 0 or negative numbers due to bad data entry.

Why it matters: A side length of 0 or a negative number can never form a real triangle, but the current query would still evaluate the math correctly in most cases (since a 0 or negative side usually fails the inequality anyway). Still, it’s worth mentioning in an interview that assuming clean, positive input is a business assumption, not something the query enforces directly. If this needed to be handled strictly, an additional check like x > 0 AND y > 0 AND z > 0 could be added to the CASE condition.


Further Questions

  • “What would happen if one of the side lengths was 0? Walk me through it.”
  • “How would you modify this query to also return the triangle type (equilateral, isosceles, scalene) for valid triangles?”
  • “Can you rewrite this logic using a boolean expression directly instead of CASE, in a database that supports returning booleans as columns?”
  • “How would this query behave if x, y, or z were NULL?”
  • “How would you test this query to make sure it handles edge cases correctly?”

Similar Problems

  • Range-based classification problems (similar structure to Example 1 from the CASE Expression concept notes: checking a value against multiple threshold conditions)
  • Problems that classify rows based on multiple combined conditions using AND/OR logic
  • Problems that extend a Yes/No check into a multi-category classification (for example, classifying a triangle as Equilateral, Isosceles, or Scalene instead of just Valid/Invalid)

Key SQL Concepts Learned

ConceptPurpose
CASE (Searched)Turns a condition into a labeled Yes/No output
ANDCombines multiple conditions, all of which must be true together
Arithmetic in WHERE/CASEPerforms calculations (like x + y) directly inside a condition
ELSECatches every row that does not fully satisfy the WHEN condition

Pattern Recognition

When should you immediately think of this approach?

  • Need to check if all of several conditions are true at once → combine with AND inside CASE
  • Need a Yes/No or Pass/Fail label based on a rule → CASE
  • Need to check a mathematical rule involving three or more related values in the same row → do the math directly inside the CASE condition, no subquery or join needed
  • Rule involves checking every possible pairing among values (like all three sides of a triangle) → make sure every pairing is explicitly written out, don’t assume checking one pairing is enough

In this topic

Done with this topic?

How well do you know it?

PreviousAggregation Problems