1

I have a table, let's say:

id | value
1  |  'a'
2  |  'b'

Where for some ID's value might be missing. If I use iterative solution, for example:

for item in my_array:
   data = cursor.execute("""SELECT id from table WHERE value = 'a'""")

If there is no 'a' in DB I get None and can handle it, so for each item I have at least None. But what if I want to do all at once, like:

"""SELECT id from table WHERE value = ANY(array['a', 'b', 'c', 'd'])"""

So I need 4 responses (including None for missing data), while it gives me response only for present data

2 Answers 2

2

In SQL, you need to generate the data and use left join. In Postgres, you can do:

select v.value, t.id
from (values ('a'), ('b'), ('c'), ('d')) v(value) left join
     table t
     on t.value = v.value;
Sign up to request clarification or add additional context in comments.

1 Comment

a cross join on distinct id's is needed before a left join.
1

You need to join the table with itself:

select t.id as orig_id, filtered.id as filtered_id
from <table> t
left join(
    select * from <table> where value = ANY(ARRAY[29, 30, 31, 32])
) filtered
on t.id = filtered.id
order by t.id

results in:

orig_id |filtered_id |
--------|------------|
...
22      |            |
27      |            |
28      |            |
29      |29          |
30      |30          |

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.