Skip to content

Instantly share code, notes, and snippets.

@ilovejs
Created July 12, 2018 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilovejs/b3360db85dc020148f411867c5dce081 to your computer and use it in GitHub Desktop.
Save ilovejs/b3360db85dc020148f411867c5dce081 to your computer and use it in GitHub Desktop.
CTE has limitation
--https://www.citusdata.com/blog/2018/05/15/fun-with-sql-recursive-ctes/
--Return: x
WITH RECURSIVE tens(x) AS (
SELECT 10
UNION
SELECT x + 10 FROM tens WHERE x + 10 <= 100
)
SELECT x FROM tens;
--Without having to drop down to a procedural language like plpgsql or plv8.
--Ex.1
DROP TABLE employees;
CREATE TABLE employees (
id serial PRIMARY KEY,
name varchar(255),
manager_id int
);
INSERT INTO employees VALUES (1, 'Umur', null);
INSERT INTO employees VALUES (2, 'Craig', 1);
INSERT INTO employees VALUES (3, 'Daniel', 2);
INSERT INTO employees VALUES (4, 'Claire', 1);
INSERT INTO employees VALUES (5, 'Lindsay', 2);
INSERT INTO employees VALUES (6, 'Will', 2);
INSERT INTO employees VALUES (7, 'Burak', 2);
INSERT INTO employees VALUES (8, 'Eren', 2);
INSERT INTO employees VALUES (9, 'Katie', 3);
INSERT INTO employees VALUES (10, 'Teresa', 4);
SELECT * FROM employees;
--No params
--Skip if manager_id is NULL
WITH RECURSIVE print_manager AS (
SELECT id, name, manager_id FROM employees WHERE id = 2 --change to 3 :)
UNION ALL
SELECT e.id, e.name, e.manager_id
FROM employees e
INNER JOIN print_manager pm ON pm.id = e.manager_id --can't be (outer) left join
)
SELECT id, "name", manager_id FROM print_manager;
WITH RECURSIVE print_manager AS (
SELECT id, name, manager_id FROM employees WHERE id = 8
UNION
SELECT e.id, e.name, e.manager_id FROM employees e
JOIN print_manager pm ON pm.id = e.manager_id --future row start from 8th, won't contains any id = 2...so it stopped.
)
SELECT id, "name", manager_id FROM print_manager;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment