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)