Postgres - Counting children in level (below) using ltree

I have a table

CREATE TABLE foo (text name, path ltree);

A couple of inserts

INSERT INTO foo (name, path) VALUES ( 'Alice', 'ROOT.first.parent');
INSERT INTO foo (name, path) VALUES ( 'Bob', 'ROOT.second.parent');
INSERT INTO foo (name, path) VALUES ( 'Mistress', 'ROOT.third.parent');
INSERT INTO foo (name, path) VALUES ( 'Ted', 'ROOT.first.parent.child');
INSERT INTO foo (name, path) VALUES ( 'Carol', 'ROOT.second.parent.child');

Now I simply want to count the nodes under ROOT. I think I should do:

SELECT count(path) FROM foo
WHERE path ~ 'ROOT.*{1}'

I would expect 3 but I get 0. Any ideas?

Answers


You'd need either

WHERE path ~ 'ROOT.*{2}'

or

WHERE path ~ 'ROOT.*.parent'

That's because 'first.parent' is two labels, not one. The second WHERE clause looks for paths that end with 'parent', which I think makes your intent clearer.

You can see the sqlfiddle here.


Fount it! As with all things, RTFM is not a bad advice. The bundled Subpath function does the trick. Count distinct occurrences from offset 1, length 1:

select count(distinct subpath(path, 1, 1))
from foo

3.


Need Your Help

C++ Dynamic Array Inputs

c++ io dynamic-arrays

I am using two dynamic arrays to read from a file. They are to keep track of each word and the amount of times it appears. If it has already appeared, I must keep track in one array and not add it ...

Why doesn't my 'sort' function work? I cant find any errors I did

javascript html arrays sorting object

I am toying around with objects in javascript to get a better grasp on my ability to use functions, and manipulate objects. I have a program that 'builds' an Array of Objects. Each of those 'obje...