SQL Boy
TutorialsPlayground

Format & Validate

SQL FormatterSQL MinifierSyntax Validator

Convert

JSON to SQLCSV to SQLSQL to JSONRegex to SQLExcel to SQLSQL Dialect Convertersoon

Visualize

ER Diagram GeneratorSQL Schema Diff

Generate

SQL Mock Data Generator

Analyze

SQL Query ExplainerSQL Query Analyzer

Workflow hubs

FormattingConversionSchemaAnalysis
View all tools
Daily ChallengeInterviewsCheat SheetBlog

© 2026 SQL Boy. Built for developers.

ContactPrivacyTermsAI Usage PolicyEditorial StandardsAboutRSS Feed

New conversation

What can I help with?

Ask about this page, get a hint on a challenge, or explore SQL concepts.

I know what's on this page and can give answers grounded in SQL Boy content.

Current page

Tree Node

/challenges/tree-node

Usage status will load after login
SQL Boy
TutorialsPlayground

Format & Validate

SQL FormatterSQL MinifierSyntax Validator

Convert

JSON to SQLCSV to SQLSQL to JSONRegex to SQLExcel to SQLSQL Dialect Convertersoon

Visualize

ER Diagram GeneratorSQL Schema Diff

Generate

SQL Mock Data Generator

Analyze

SQL Query ExplainerSQL Query Analyzer

Workflow hubs

FormattingConversionSchemaAnalysis
View all tools
Daily ChallengeInterviewsCheat SheetBlog
SQL Challenges/Tree Node
Challenge DetailMediumReviewed 2026-04-20

Tree Node

Each node in the tree can be one of three types: "Leaf": if the node is a leaf node. "Root": if the node is the root of the tree. "Inner": If the node is neither a leaf node nor a root node.

Case WhenSubqueriesJoin

This challenge now meets the current minimum standard for sitemap inclusion and independent indexing.

2026-01-19Medium

Tree Node

Each node in the tree can be one of three types: "Leaf": if the node is a leaf node. "Root": if the node is the root of the tree. "Inner": If the node is neither a leaf node nor a root node.

Available Tables:
SQL Editor
Loading...

What This Challenge Is Testing

Hierarchical data appears everywhere: org charts, menus, categories, and dependency trees. This problem is a simple introduction to reasoning about parent-child structure inside one table, which is the foundation for more advanced recursive SQL later.

Topic Tags

Case WhenJoins

Schema At A Glance

tree
idp_id

Solution Approaches

01

CASE with parent and child existence checks

SELECT
  id,
  CASE
    WHEN p_id IS NULL THEN 'Root'
    WHEN id IN (SELECT p_id FROM tree WHERE p_id IS NOT NULL) THEN 'Inner'
    ELSE 'Leaf'
  END AS type
FROM tree

The logic mirrors the node definitions directly. A root has no parent, an inner node appears as someone else’s parent, and everything left over is a leaf.

02

LEFT JOIN children for an explicit child check

SELECT
  t1.id,
  CASE
    WHEN t1.p_id IS NULL THEN 'Root'
    WHEN t2.id IS NOT NULL THEN 'Inner'
    ELSE 'Leaf'
  END AS type
FROM tree t1
LEFT JOIN tree t2
  ON t1.id = t2.p_id
GROUP BY t1.id, t1.p_id

The join version makes child existence explicit by linking each node to any rows that name it as a parent. It is often easier to extend when the next question asks for child counts or subtree metrics.

Common Pitfalls

Do not identify leaves solely by checking p_id IS NOT NULL. A non-root node can still be an inner node if other rows reference it as their parent. You must check both parent status and child existence.

Frequently Asked Questions

Why is a root not also considered an inner node if it has children?

Because the prompt defines root as its own category. The classification is mutually exclusive: root first, then inner, then leaf.

What SQL concept does this teach beyond CASE?

It teaches you to reason about self-referential tables, where the same relation plays both the parent role and the child role at the same time.

Concept Guides

Use these guides when you want the fuller explanation behind the SQL pattern this challenge is testing.

Mastering Recursive CTEs: The Inception of SQL

Unlock the power of WITH RECURSIVE. Learn how to traverse hierarchies, generate continuous dates, and solve graph problems directly in SQL.

SQL CASE Statements: Adding Logic to Your Queries

Learn how to add conditional logic to your SQL queries using CASE statements. Transform data and categorize results with ease.

SQL Table Relationships: One-to-Many and Many-to-Many

Learn the two most important database relationships. Design one-to-many and many-to-many tables with real SQL examples, diagrams, and interactive queries.

Topic Hubs

If this problem exposed a deeper weakness, use a topic hub to move through a curated cluster instead of random article hopping.

Advanced SQL

Advanced query patterns

Use this path when you are moving beyond beginner SELECT queries into CTEs, window functions, and conditional logic.

Schema

Schema design and data modeling

Useful when the hard part is not the query itself but the table design, relationships, and semi-structured data underneath it.

Practice Path

If you want the rotating practice flow, open this same question from the daily stream. If you want interview-style packaging, continue into the interview pool after this rep.

Back to ChallengesOpen In DailyBrowse Interviews

Related Challenges

Exchange SeatsMedium

Swap every pair of adjacent seat IDs while leaving the final row untouched if the seat count is odd.

Friend Requests I: Overall Acceptance RateMedium

Calculate overall friend request acceptance rate while separating request volume from accepted pairs cleanly.

Customers Who Bought All ProductsMedium

Return only the customers whose distinct purchased product set covers every product listed in the catalog.

© 2026 SQL Boy. Built for developers.

ContactPrivacyTermsAI Usage PolicyEditorial StandardsAboutRSS Feed