

) SEARCH BREADTH FIRST BY id SET ordercol SELECT * FROM search_tree ORDER BY ordercol There is built-in syntax to compute a depth- or breadth-first sort column. The order of the rows within each level is certainly undefined, so some explicit ordering might be desired in any case. However, this is an implementation detail and it is perhaps unsound to rely on it. The recursive query evaluation algorithm produces its output in breadth-first search order. SELECT t.id, t.link, t.data, path || ROW(t.f1, t.f2) For example, if we needed to track fields f1 and f2: In the general case where more than one field needs to be used to identify a row, use an array of rows. SELECT t.id, t.link, t.data, path || t.id WITH RECURSIVE search_tree(id, link, data, path) AS ( To add depth-first ordering information, you can write this: WITH RECURSIVE search_tree(id, link, data) AS (

For example, consider the following query that searches a table tree using a link field: To create a depth-first order, we compute for each result row an array of rows that we have visited so far. This approach merely provides a convenient way to order the results afterwards. Note that this does not actually control in which order the query evaluation visits the rows that is as always in SQL implementation-dependent. This can be done by computing an ordering column alongside the other data columns and using that to sort the results at the end. When computing a tree traversal using a recursive query, you might want to order the results in either depth-first or breadth-first order.
