Monday, May 26, 2008

Hierarchical data with SQL Query

Here is what SQL gives to avoid recursion in program.
You can get parents in tree like hierarchy.

WITH [ RECURSIVE ]  [ (  ) ]
AS ( )


The use of only the WITH clause (without the keyword RECURSIVE), is to
build a Common Table Expression (CTE). In a way CTE is a view build
especially for a query and used in one shot: each time we execute the
query. In one sense it can be called a "non persistent view".
A simple example for you.

SELECT COUNT(NEW_ID) AS NEW_NBR, NEW_FORUM
FROM T_NEWS
GROUP BY NEW_FORUM

WITH
Q_COUNT_NEWS (NBR, FORUM)
AS
(
SELECT COUNT(NEW_ID), NEW_FORUM
FROM T_NEWS
GROUP BY NEW_FORUM),
Q_MAX_COUNT_NEWS (NBR)
AS (SELECT MAX(NBR)
FROM Q_COUNT_NEWS
)
SELECT T1.*
FROM Q_COUNT_NEWS T1
INNER JOIN Q_MAX_COUNT_NEWS T2
ON T1.NBR = T2.NBR

With this query you can get output like.

ALL
|--SEA
| |--SUBMARINE
| |--BOAT
|--EARTH
| |--CAR
| |--TWO WHEELES
| | |--MOTORCYCLE
| | |--BYCYCLE
| |--TRUCK
|--AIR
|--ROCKET

So use this SQL advantage to lower the program overheads.
|--PLANE

0 comments:

Disk Doctor Utility