I'm curious to know how people are using table aliases. The other developers where I work always use table aliases, and always use the alias of a, b, c, etc.
Here's an example:
SELECT a.TripNum, b.SegmentNum, b.StopNum, b.ArrivalTime FROM Trip a, Segment b WHERE a.TripNum = b.TripNum
I disagree with them, and think table aliases should be use more sparingly.
I think they should be used when including the same table twice in a query, or when the table name is very long and using a shorter name in the query will make the query easier to read.
I also think the alias should be a descriptive name rather than just a letter. In the above example, if I felt I needed to use 1 letter table alias I would use t for the Trip table and s for the segment table.
TABLE ALIASES are used to shorten your SQL to make it easier to read or when you are performing a self join (ie: listing the same table more than once in the FROM clause).
Alias refers to the practice of using a different temporary name (usually a short name or a name with a logical meaning) to a database table or a column in a table. The main advantage of using an alias is to help make the SQL statement more concise and readable.
Aliases are created to make table or column names more readable. The renaming is just a temporary change and table name does not change in the original database. Aliases are useful when table or column names are big or not very readable.
The alias doesn't affect performance in any practical or measurable way at all (italics added on edit). That is, it would add a barely (if it all) measurable delay to query compilation. Once compiled (and re-used), it has no effect.
There are two reasons for using table aliases.
The first is cosmetic. The statements are easier to write, and perhaps also easier to read when table aliases are used.
The second is more substantive. If a table appears more than once in the FROM clause, you need table aliases in order to keep them distinct. Self joins are common in cases where a table contains a foreign key that references the primary key of the same table.
Two examples: an employees table that contains a supervisorID column that references the employeeID of the supervisor.
The second is a parts explosion. Often, this is implemented in a separate table with three columns: ComponentPartID, AssemblyPartID, and Quantity. In this case, there won't be any self joins, but there will often be a three way join between this table and two different references to the table of Parts.
It's a good habit to get into.
I use them to save typing. However, I always use letters similar to the function. So, in your example, I would type:
SELECT t.TripNum, s.SegmentNum, s.StopNum, s.ArrivalTime FROM Trip t, Segment s WHERE t.TripNum = s.TripNum
That just makes it easier to read, for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With