Giving Better Names to Query Result Columns

Problem

You don’t like the names of the columns in a query result.

Solution

Use column aliases to supply names of your own choosing.

Discussion

When you retrieve a result set, MySQL gives every output column a name. (That’s how the mysql program gets the names that you see displayed as the initial row of column headers in result set output.) By default, MySQL assigns the column names specified in the CREATE TABLE or ALTER TABLE statement to output columns, but if these defaults are not suitable, you can use column aliases to specify your own names.

This section explains aliases and shows how to use them to assign column names in statements. If you’re writing a program that needs to retrieve information about column names (that is, column metadata), see Obtaining Result Set Metadata.

If an output column in a result set comes directly from a table, MySQL uses the table column name for the output column name. For example, the following statement selects three table columns, the names of which become the corresponding output column names:

mysql>SELECT t, srcuser, size FROM mail;
+---------------------+---------+---------+
| t                   | srcuser | size    |
+---------------------+---------+---------+
| 2006-05-11 10:15:08 | barb    |   58274 |
| 2006-05-12 12:48:13 | tricia  |  194925 |
| 2006-05-12 15:02:49 | phil    |    1048 |
| 2006-05-13 13:59:18 | barb    |     271 |
...

If you generate a column by evaluating an expression, the expression itself is the column name. This can ...

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.