Skip to content

Instantly share code, notes, and snippets.

@nwjsmith
Created December 20, 2015 21:43
Show Gist options
  • Save nwjsmith/8a75e6aaaffb9ccfe77e to your computer and use it in GitHub Desktop.
Save nwjsmith/8a75e6aaaffb9ccfe77e to your computer and use it in GitHub Desktop.
Recursive ancestors query for PostgreSQL
WITH RECURSIVE ancestors(id, name, created_at, updated_at) AS (
SELECT categories.id, categories.name, categories.created_at, categories.updated_at
FROM categories, categorizations
WHERE categorizations.subcategory_id = '667C9DF5-48C0-496B-922A-1B7D743B1A39'
AND categories.id = categorizations.category_id
UNION ALL
SELECT categories.id, categories.name, categories.created_at, categories.updated_at
FROM categories, categorizations, ancestors
WHERE categorizations.subcategory_id = ancestors.id
AND categories.id = categorizations.category_id
)
SELECT * FROM ancestors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment