2

The filter in the following query are identical.

select * from t_profile where 
profile_id in        (select profile_id from t_profile ...) or 
active_profile_id in (select profile_id from t_profile ...);

Can we avoid repeating the filter?

2
  • 2
    You can do a JOIN instead. Or EXISTS. Commented Feb 27, 2018 at 10:19
  • A join perhaps? Commented Feb 27, 2018 at 10:19

3 Answers 3

2

You can use a common table expression for that:

with filter as (
   select profile_id 
   from ...
   where ...
)
select *
from t_profile
where profile_id in (select profile_id from filter)
   or active_profile_id in (select profile_id from filter);
Sign up to request clarification or add additional context in comments.

1 Comment

I couldn't vote due to my little reputation, thanks!
0

You can JOIN:

SELECT * FROM T_profile1 AS t1
JOIN T_Profile2 AS t2
ON t1.profile_id = t2.profile_id 
 OR t1.active_Profile_id = t2.profile_id

If you don't want repeating columns, you can do separate queries and UNION them

SELECT * FROM T_profile1 AS t1
JOIN T_Profile2 AS t2
ON t1.profile_id = t2.profile_id

UNION

SELECT * FROM T_profile1 AS t1
JOIN T_Profile2 AS t2
ON t1.active_Profile_id = t2.profile_id

I recommend you reading https://www.w3schools.com/sql/default.asp for more SQL fundamentals

3 Comments

A join is not necessarily the same thing as an IN condition.
After I saw the CTE answer, I agree it is better. Nonetheless, Join is not the same thing, because data in the columns can be used in select part of the query. Also in the first example there is no repeating code.
Do you mean? SELECT * FROM T_profile AS t1 JOIN T_Profile AS t2 ON t1.profile_id = t2.profile_id OR t1.active_Profile_id = t2.profile_id; This does not work.
0

You can avoid repeating the filter by using exists rather than in:

select p.*
from t_profile p
where exists (select 1
              from t_profile p2 . . .
              where p2.profile_id = p.profile_id or
                    p2.profile_id = active_profile_id
             );

That said, repeating the filter using either in or exists is probably the better option.

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.