tags:

views:

46

answers:

2

Can we have multiple alias names for a single table?

+6  A: 

Yes. You need to do this for a self join, for example f you have a table storing a hierarchy:

create table Foo (
    FooID int
   ,ParentFooID int
   ,[columns]
)

You can do a join to get the children of parents that satisfy a particular condition with a query like:

Select b.*
  from Foo a
  join Foo b
    on a.FooID = b.ParentFooID
   and [some condition filtering a]
ConcernedOfTunbridgeWells
+1 for powers of inference!
Ed Harper
But it will effect the performance or not?
Dev
The query optimiser will have to do whatever is necessary to resolve the join predicate. For example, if the table is large and has an index on ParentFooID, it will probably have to do index lookups to resolve the FooID - ParentFooID join. Doing the match will always involve some resources.
ConcernedOfTunbridgeWells
We do this a lot (representing a heirarchy in SQL.) Performance is fine, and it's a good, flexible system - although the queries can get a little involved. It works. (p.s. good inference!)
Ragster
@Dev, almost certainly not - but there's one way to find out...
Mark Bannister
A: 

No not on the same table, but you can select the same table twice and give each a different alias.

SELECT alias1.*, alias2.*
FROM table alias1, table alias2

This will then allow you to use the same table for a different purpose within a single query.

Chris Diver
But it will effect the performance or not?
Dev
Yes, if you select the table twice then it will have to do twice as much work. Performance will depend on how they are used, what they are joined two and the indexes and statistics available to the query optimizer.
Chris Diver
Since Chris's query has no join condition (implicit or explict) a cartesian join would be expected - ie. every single row in table will be linked with all the rows in the same table, so if you had 20 rows in table your resultset would be 400 rows! This is much worse than twice as much work. However, it's not the aliases that are causing the work - it's the cartesian join.
Mark Bannister
The cross join was just an example to which I wasn't referring to when answering the comment - the OP did not specify how he was going to use the tables, I'd assume he will either self join or join them to different tables. Like I said performance will depend on how they are used.
Chris Diver