📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you prevent cycles when users can move nodes in a hierarchy stored as an adjacency list?

Mid-Level Sql Intermediate

🎯 Key points

  • Check ancestors of the new parent for the moving node
  • Recursive CTE walking upwards
  • Same transaction with UPDLOCK/HOLDLOCK to stop concurrent moves
  • CHECK constraint for self-parenting
  • Read-time path check stays as a safety net

⏱ 30-second answer

Validate on write: before setting ParentId = @newParent for node @id, run a recursive CTE from @newParent up to the root and reject the move if @id appears among its ancestors. Do the check and update in one transaction with UPDLOCK, HOLDLOCK (or serializable) on the affected rows so two concurrent moves can't create a cycle together. Add CHECK (ParentId <> Id) for the trivial case.

🔍 What the interviewer is checking

Checks whether they fix bad data at write time, not only at read time.

↩ Usually asked after

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me