开发者

whats is the importance of table alias in sql join query?

开发者 https://www.devze.com 2023-04-12 15:31 出处:网络
I wrote a sql join query in oracle with two table. While writing query I did not use any table alias to refer column in select clause.

I wrote a sql join query in oracle with two table. While writing query I did not use any table alias to refer column in select clause. Now this was possible because the selected columns were having different names in both the tables.

So the question follows; is it necessary (from performance point of view) to use a table alias to select column regardless there is any similar column name开发者_开发百科 in both the tables?

Please note: Right now I am under impression that "In case of join query when we do not specify table alias to select column oracle will always lookup the table metadata to find out which table has this column." So is my assumption true?

Thanks, hanumant


No, your assumption is not true.

There are at least four reasons to use table aliases:

  • If the alias is shorter than the name it allows you to type less.
  • If you self-join a table you are required to give an alias to one or both of the tables to allow you to distinguish between them.
  • Derived tables must have an alias in some database systems (not Oracle though, I think).
  • The alias can make it clearer what the role of the table is in that particularly query.

There is no significant performance penalty from using them.


To make it simple...

This fails

select 
ID,
ID
from table1 
inner join table2  on table1.ID = table2.AnotherID

This doesn't fail

select 
a.ID,
b.ID
from table1 a
inner join table2 b on a.ID = b.AnotherID

The reason the first one fails is because the Optimization Engine does not know which table to pull the ID field from. With the alias - you give it a "hint" as to which table to use. The alias is just a substitute for the full table name.

You also have to be careful where you try to access the aliased tables. For more information on this check out the SQL order of operations.

0

精彩评论

暂无评论...
验证码 换一张
取 消