What is the standard SQL query equivalent to Oracle's 'start with...connect by', but not DBMS specific

StackOverflow https://stackoverflow.com/questions/13301750

Question

I would like to know if there is a generic SQL equivalent to Oracle's hierarchical syntax start with...connect by. I need something which can be used on any database. Here is the sort of query I mean (using Oracle's example EMP table):

SELECT empno , ename , job , mgr ,hiredate ,level 
FROM emp 
START WITH mgr IS NULL 
CONNECT BY PRIOR empno = mgr. 

Recursive Common Table Expressions work for many database implementations but not for MySQL.

Was it helpful?

Solution

There is no way of doing this in MySQL. There are some nasty hacks listed in an article by Mike Hillyer which could be used in other databases as well. But using something as inelegant as the Nested Set model in Oracle just so the same code will run on MySQL seems perverse.

The generic way would be CTE, as they are specified in SQL-99, and most flavours of RDBMS support it (even Oracle added recursiveness to its CTEs in 11gR2). The lack of support for CTE in MySQL was raised as a bug in 2006. Perhaps now Oracle owns MySQL they will get around to implementing it.

However, it really depends on your business reasons for wanting a generic solution and which database versions you really need to cover. It is a truism of writing database applications which can run on any RDBMS that they run well on none of them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top