1

Given below table in Postgres:

id some_col
1 a
1 b
2 a
3 a

I want to get output as id and true (if at least one row with that id is present in the table) or false (if no rows with that id are found in the table).

For example where id in (1, 2, 3, 4, 5):

id value
1 true
2 true
3 true
4 false
5 false

I tried with the group by and case with conditions, but is there any optimized/performance SQL way of achieving this? Bcz, groupby does complete rows count which is unnecessary in this scenario. And, with exists query I didn't find a way to deal with multiple rows return;

Thanks in Advance!

1
  • 1
    You need to OUTER JOIN the values 1 - 5.
    – jarlh
    Jan 20, 2022 at 11:38

1 Answer 1

3

The in clause won't do it. You need to build a list of values somehow (the values table valued constructor works in most rdbms) and outer join with it:

SELECT x.id, EXISTS (
    SELECT *
    FROM t
    WHERE t.id = x.id
) AS value
FROM (VALUES (1), (2), (3), (4), (5)) AS x(id)
6
  • could you pls explain if this would count all rows for each id internally? Bcz for each id, I may how thousands of rows in my case. I want to eliminate that.
    – Forece85
    Jan 20, 2022 at 11:56
  • 1
    You don't need the CASE expression. EXISTS() already yields a boolean. Jan 20, 2022 at 11:57
  • would limit 1 to subquery help for your answer?
    – Forece85
    Jan 20, 2022 at 11:57
  • Added limit 1 to the subquery of your answer. It worked. Thankyou.
    – Forece85
    Jan 20, 2022 at 11:59
  • 1
    @Forece85 no limit is not required. It is wrapped inside exists so basically it means check for presence of rows - 1 row or 1000 rows does not matter.
    – Salman A
    Jan 20, 2022 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.