SQL Issue: Short Table Aliases

in sql •  7 years ago 

I often see queries that use short names for table aliases. The queries look something like this.

SELECT a.Column2
FROM   Table1 AS a
INNER JOIN Table2 AS b ON a.Column1 = b.Column1

Table aliases are great. They often make queries much easier to read. But if it's difficult to mentally map the alias to the real table name, they often make the queries more difficult to read.

For example, if multiple tables participate in the query, it starts to get harder to read.

SELECT a.Column5
       b.Column6
FROM   Table1 AS a
INNER JOIN Table2 AS b ON a.Column1 = b.Column1
INNER JOIN Table2 AS c ON b.Column2 = c.Column2
INNER JOIN Table2 AS d ON c.Column3 = d.Column3
INNER JOIN Table2 AS e ON d.Column4 = e.Column4

At some point, it takes longer to read than if aliases weren't used at all.

I think a lot of this stems from the lack of good tooling for databases. It wasn't until (relatively) recently that autocomplete was standard in IDEs. And even now, it's not a polished feature. So if you grew up having to write the queries in an older IDE, shorter names were great. But it's not required in today's world. Modern IDEs will autocomplete table names and format queries to use consistent formatting. We should use these tools to our advantage.

One final note. Using short table aliases often makes the FROM clause easier to read. This is because it makes the line of text shorter. Compare the two queries below. However, the SELECT statement is clearer without the aliases. A compromise might be to use abbreviations which are still descriptive, but shorter in length. See the third example below.

SELECT e.FirstName
     , c.GroupName
FROM   Employee AS e
       INNER JOIN Organization AS o ON o.EmployeeId = e.EmployeeId
       INNER JOIN Building AS b ON b.BuildingId = o.BuildingId
       INNER JOIN Parking AS p ON p.BuildingId = b.BuildingId
       INNER JOIN Carpool AS c ON c.CarpoolId = p.CarpoolId
SELECT Employee.FirstName
     , Carpool.GroupName
FROM   Employee
       INNER JOIN Organization ON Organization.EmployeeId = Employee.EmployeeId
       INNER JOIN Building ON Building.BuildingId = Organization.BuildingId
       INNER JOIN Parking ON Parking.BuildingId = Building.BuildingId
       INNER JOIN Carpool ON Carpool.CarpoolId = Parking.CarpoolId
SELECT emp.FirstName
     , Carpool.GroupName
FROM   Employee AS emp
       INNER JOIN Organization AS org ON org.EmployeeId = emp.EmployeeId
       INNER JOIN Building AS bld ON bld.BuildingId = org.BuildingId
       INNER JOIN Parking AS park ON park.BuildingId = bld.BuildingId
       INNER JOIN Carpool ON Carpool.CarpoolId = park.CarpoolId
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

@resteemator is a new bot casting votes for its followers. Follow @resteemator and vote this comment to increase your chance to be voted in the future!