Introduction
When dealing with hierarchical data, we usually use recursion for constructing
the tree structure. It would be a performance problem if you query the tree node
data from the database every time the recursion happens. Also, if you work with
languages which are heavily based on callback like Javascript, you will find it
is very difficult to deal with the recursion because you have to determine when
the callback has finished execution. Luckily, PostgreSQL supports recursive
query using the WITH RECURSIVE
keyword. All the data structure can be returns
within a single query.
WITH queries in PostgreSQL
According to PostgreSQL document, WITH
queries provide a method for dealing
with large queries by creating temporary tables that exist only for that query.
This is a very simple example from Postgres document to illustrate the usage of
WITH
queries.