0

I have a table which has these columns: id, text, parentid. And when a row is a root item (doesn't have any parent item), then parentid = 0.

What I want to do, is find text of the first root (root of root of ... root of item) of a specific item.

Here's an example:

SELECT parentid FROM cat WHERE id = 1234 --returns 1120
SELECT parentid FROM cat WHERE id = 1120 --returns 1011
SELECT parentid FROM cat WHERE id = 1011 --returns 0. So this the first root.
SELECT text FROM cat WHERE id = 1011 --returns what I want.

I know it's easily possible with Loops, but I'm using sqlite which doesn't support loops.

So, the question is, is there any way to implement this in sqlite without using any other scripts?

4
  • You can use a recursive cte Commented Jul 2, 2014 at 22:27
  • @Blorgbeard I can't understand how it works. Can you please explain it a bit more, and post it as an answer? Commented Jul 2, 2014 at 22:31
  • Oops, something was wrong in the example. (Last query, number should be 1101 not 1120) I just edited it. Commented Jul 2, 2014 at 22:36
  • I don't have time to spend on that right now, but maybe someone else will. There are copious examples on that page, you could probably figure it out. Commented Jul 2, 2014 at 22:37

1 Answer 1

2

This recursive CTE will give you the desired result. Please note that the CTEs are available only in the latest versions of SQLite starting from version 3.8.3

;with cte as (
  select id, parentid, text, 1 level 
  from t where id = 1234
  UNION all
  select t.id, t.parentid, t.text, cte.level + 1 
  from cte inner join t on cte.parentid = t.id 
  where cte.parentid <> 0)
select * from cte where parentid = 0
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for mentioning the necessary SQLite version. I had to update my SQLite libraries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.