Search code examples
sqlscopetable-alias

SQL - table alias scope


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' )      
  1. 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?

  2. I have had the RDBMS complain: "only the first 1000 rows might be retrieved". Would this second approach solve that problem?

  3. 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 (o for table and othertable) in the second exist will it present any problem with the first exist? Or are they independent?

Is this only Oracle-related or it is valid for most RDBMSs?


Solution

  • 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:

    select t.* 
    from table t 
    join othertable o on t.nameid = o.nameid 
        and o.otherdesc in ('SomeDesc','SomeOtherDesc');
    

    And, to answer your questions:

    1. Yes
    2. Yes
    3. Yes