szymon_dybczak
Esteemed Contributor III

Hi @saurabh_aher ,

Look at documentation example. You can't use order by with limit at the same time, because order by prevents early termination of recursion. Load the content of your cte with limit applied to delta table and then you can do whatever you want (I mean order the data according to your needs).

szymon_dybczak_0-1753960845563.png

WITH RECURSIVE hierarchy AS (
-- Anchor: start with each employee as their own root (level 0)
SELECT
e.id AS root_id,
e.name AS root_name,
e.id AS emp_id,
e.name AS emp_name,
e.managerId,
0 AS level_id
FROM employees e

UNION ALL

-- Recursive part: find all subordinates
SELECT
h.root_id,
h.root_name,
e.id AS emp_id,
e.name AS emp_name,
e.managerId,
h.level_id + 1 AS level_id
FROM hierarchy h
JOIN employees e
ON e.managerId = h.emp_id
)
SELECT *
FROM hierarchy
LIMIT 150000 /*Put here your number*/