Skip to content

Instantly share code, notes, and snippets.

@mmousawy
Last active February 27, 2024 01:48
Show Gist options
  • Save mmousawy/654227deb569497205a944e517878aa9 to your computer and use it in GitHub Desktop.
Save mmousawy/654227deb569497205a944e517878aa9 to your computer and use it in GitHub Desktop.
Recursive SQL SELECT, UPDATE and DELETE with recursive CTE in MariaDB
-- SELECT
WITH recursive custom_cte AS
( SELECT
*
FROM
target_table
WHERE
target_table.id = "value"
UNION ALL
SELECT
a.*
FROM
target_table a
INNER JOIN
custom_cte b
ON
a.parent = b.id
)
SELECT
*
FROM
custom_cte
-- UPDATE
UPDATE
target_table AS table_alias
JOIN
( SELECT
*
FROM
( WITH recursive custom_cte AS
( SELECT
*
FROM
target_table
WHERE
target_table.id = "value"
UNION ALL
SELECT
a.*
FROM
target_table a
INNER JOIN
custom_cte b
ON
a.parent = b.id
)
SELECT
*
FROM
custom_cte
) AS x
) AS to_update
ON
table_alias.id = to_update.id
SET
table_alias.column = value
-- DELETE
DELETE table_alias FROM
target_table AS table_alias
JOIN
( SELECT
*
FROM
( WITH recursive custom_cte AS
( SELECT
*
FROM
target_table
WHERE
target_table.id = "value"
UNION ALL
SELECT
a.*
FROM
target_table a
INNER JOIN
custom_cte b
ON
a.parent = b.id
)
SELECT
*
FROM
custom_cte
) AS x
) AS to_update
ON
table_alias.id = to_update.id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment