Using Column Aliases to Make Programs Easier to Write

Problem

You’re trying to refer to a column by name from within a program, but the column is calculated from an expression. Consequently, its name is difficult to use.

Solution

Use an alias to give the column a simpler name.

Discussion

Giving Better Names to Query Result Columns shows how column aliases make query results more meaningful when you’re issuing queries interactively. Aliases also are useful for programming purposes. If you’re writing a program that fetches rows into an array and accesses them by numeric column indexes, the presence or absence of column aliases makes no difference because aliases don’t change the positions of columns within the result set. However, aliases make a big difference if you’re accessing output columns by name because aliases change those names. You can exploit this fact to give your program easier names to work with. For example, if your query displays reformatted message time values from the mail table using the expression DATE_FORMAT(t,'%M %e, %Y'), that expression is also the name you’d have to use when referring to the output column. That’s not very convenient. If you use ASdate_sent to give the column an alias, you can refer to it a lot more easily using the name date_sent. Here’s an example that shows how a Perl DBI script might process such values. It retrieves rows into a hash and refers to column values by name:

$sth = $dbh->prepare ("SELECT srcuser, DATE_FORMAT(t,'%M %e, %Y') AS date_sent ...

Get MySQL Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.