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, it’s difficult to use.
Solution
Use an alias to give the column a simpler name.
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\n", $ref->{srcuser}, $ref->{date_sent};
}In Java, you’d do something like this:
Statement s = conn.createStatement ( ); s.executeQuery ("SELECT srcuser," ...