Using Column Aliases to Make Programs Easier to Write
3.5.1 Problem
You're trying to refer to a column by name from within a program, but the column is calculated from an expression. Consequently, it's difficult to use.
3.5.2 Solution
Use an alias to give the column a simpler name.
3.5.3 Discussion
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 AS date_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:
$sth = $dbh->prepare ( "SELECT srcuser, DATE_FORMAT(t,'%M %e, %Y') AS date_sent FROM mail"); $sth->execute ( ); while (my $ref = $sth->fetchrow_hashref ( )) { printf "user: %s, date sent: %s ", $ref->{srcuser}, $ref->{date_sent}; }
In Java, you'd do something like this:
Statement s = conn.createStatement ( ); s.executeQuery ("SELECT srcuser," + " DATE_FORMAT(t,'%M %e, %Y') AS date_sent" + " FROM mail"); ResultSet rs = s.getResultSet ( ); while (rs.next ( )) // loop through rows of result set { String name = rs.getString ("srcuser"); String dateSent = rs.getString ("date_sent"); System.out.println ("user: " + name + ", date sent: " + dateSent); } rs.close ( ); s.close ( );
In PHP, retrieve result set rows using mysql_fetch_array( ) or mysql_fetch_object( ) to fetch rows into a data structure that contains named elements. With Python, use a cursor class that causes rows to be returned as dictionaries containing key/value pairs where the keys are the column names. (See Recipe 2.5.)