0

I have the following sql statement:

WITH subquery AS ( select distinct id from a_table where some_field in (1,2,) ) select id from another_table where id in subquery; 

Edit

JOIN is not an option (this is just a reduced example of a bigger query)

But that obviously does not work. The id field exists in both tables (with a different name, but values are the same: numeric ids). Basically what I want to do is filter by the result of the subquery, like a kind of intersection.

Any idea how to write that query in a correct way?

6
  • ... IN (SELECT id FROM subquery) ... But I would recommend to rewrite it as a JOIN. Commented Nov 9, 2021 at 18:05
  • But does that line execute the select for every row on another_table? I'm aware of the JOIN option, but that's not possible (that just a reduced example of another query). Commented Nov 9, 2021 at 18:09
  • Depends on what the optimizer "thinks" is best. But usually no. The CTE might even be materialized. Commented Nov 9, 2021 at 18:10
  • Oh great! Can you post that as an answer? :D Commented Nov 9, 2021 at 18:14
  • For a mere lookup I wouldn't join, but use IN or EXISTS. You only got the syntax wrong. sticky bit's IN clause should work just fine for you. Commented Nov 9, 2021 at 18:14

3 Answers 3

1

You need a subquery for the second operand of IN that SELECTs from the CTE.

... IN (SELECT id FROM subquery) ... 

But I would recommend to rewrite it as a JOIN.

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

Comments

1

Are you able to join on ID and then filter on the Where clause?

select a.id from a.table inner join b.table on a.id = b.id where b.column in (1,2) 

1 Comment

I cannot use JOIN, sorry :(
0

Since you only want the id from another_table you can use exists

with s as ( select id from a_table where some_field in (1,2) ) select id from another_table t where exists ( select * from s where s.id=t.id ) 

But the CTE is really redundant since all you are doing is

select id from another_table t where exists ( select * from a_table a where a.id=t.id and a.some_field in (1,2) ) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.