Skip to Main Content
MySQL Cookbook
book

MySQL Cookbook

by Paul DuBois
October 2002
Intermediate to advanced content levelIntermediate to advanced
1024 pages
27h 26m
English
O'Reilly Media, Inc.
Content preview from MySQL Cookbook

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," ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

MySQL Reference Manual

MySQL Reference Manual

Michael Widenius, David Axmark, Kaj Arno
High Performance MySQL

High Performance MySQL

Jeremy D. Zawodny, Derek J. Balling
MySQL Stored Procedure Programming

MySQL Stored Procedure Programming

Guy Harrison, Steven Feuerstein

Publisher Resources

ISBN: 0596001452Catalog PageErrata