0

I have used destructuring assignment terminology for my case. Some programming languages allow us to make a multiple assignment:

JavaScript:

let a, b;
[a, b] = [10, 20];

Is It possible to make something similar in PostgreSQL to avoid using of duplicated sub queries?

We have a table categories:

|-----------------------|---------------------------|------------------|
|      category_id      |     parent_category_id    |       name       |
|-----------------------|---------------------------|------------------|
|            1          |           NULL            |      'main'      | <= parent category
|-----------------------|---------------------------|------------------|
|            2          |             1             |      'sub1'      |
|-----------------------|---------------------------|------------------|
|            3          |             1             |      'sub2'      |
|-----------------------|---------------------------|------------------|

We need to make a select a only sub category by the name, but if this name belogns to a parent category, get all subcategories under that parent.

in case of name = 'main' we'll get 2 categories (category IDs: 2, 3)

in case of name = 'sub2' only 1 record (category ID: 3)

Is there a way to optimize this query:

SELECT 
    c.category_id 
FROM
    categories c 
WHERE
    c.category_id = ANY 
        (SELECT c2.category_id FROM categories c2 WHERE c2.name = $1)
    OR
    c.parent_category_id = ANY 
        (SELECT c3.parent_category_id FROM categories c3 WHERE c3.name = $1)

1 Answer 1

3

It seems you are looking for a recursive query:

with recursive tree as (
  select id, parent_id, name
  from categories
  where name = $1 --<< start with this category
  union all
  select child.id, child.parent_id, child.name
  from categories child 
     join tree parent on parent.id = child.parent_id
)
select *
from tree

Note that this will yield strange results if name isn't unique

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.