I learned to use "exists" instead of "in".
BAD
select * from table where nameid in ( select nameid from othertable where otherdesc = 'SomeDesc' )
GOOD
select * from table t where exists ( select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeDesc' )
-
The explanation was: "The reason why this is better is because only the matching values will be returned instead of building a massive list of possible results". Does that mean that while the first subquery might return 900 results the second will return only 1?
-
I have had the RDBMS complain: "only the first 1000 rows might be retrieved". Would this second approach solve that problem?
-
What is the scope of the alias in the second subquery? Does the alias only live in the parenthesis?
For example
select * from table t where exists ( select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeDesc' )and
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeOtherDesc' )That is, if I use the same alias (
ofortableandothertable) in the secondexistwill it present any problem with the firstexist? Or are they independent?
Is this only Oracle-related or it is valid for most RDBMSs?
It’s specific to each DBMS and depends on the query optimizer. Some optimizers detect IN clause and translate it.
In all DBMSes I tested, alias is only valid inside the ( )
BTW, you can rewrite the query as:
And, to answer your questions: