I have a table with categories, each category as an ID, a Name and a ParentID. The problem is that there are 3 levels, parent categories, sub categories and child categories.
I can extract parent categories with a simple SELECT and a WHERE ParentID IS NULL clause as such:
SELECT *
FROM Category
WHERE ParentID IS NULL
However, a WHERE ParentID IS NOT NULL clause will return both, sub categories as well as child categories.
I’m looking for a way to extract only sub categories, and only child categories.
Typically, for these sort of problems, it is better to use the Recursive Queries Using Common Table Expressions. Something like so:
SQL Fiddle Demo
This will give you:
How does this work?
Using this query, you can control what level of categories you want to select. For instance, for the sample data, I used in the previous demo, here is the categories tree:
This query will give you this categories tree with the new generated
CategoryLevelcolumn.Note that: In the sample data I used in the demo, there was only one parent category (the categories with
parentidIS NULL). However, the query will for work fine in case there were a lot of parent categories. And this because of the anchor query of the CTE, which is:Then, you can use the generated column
CategoryLevelto select only the child categories of the level that you are interested in.For example, if you need to select only the sub categories of the first sub categories of the root category, you can get these categories using the predicate
CategoryLevel = 2:This will give you:
SQL Fiddle Demo