Database Reference
In-Depth Information
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 must determine the names, see
Recipe 10.2
for information about accessing column metadata.
If an output column comes directly from a table, MySQL uses the table column name
for the output column name. The following statement selects four table columns, the
names of which become the corresponding output column names:
mysql>
SELECT t, srcuser, srchost, size FROM mail;
+---------------------+---------+---------+---------+
| t | srcuser | srchost | size |
+---------------------+---------+---------+---------+
| 2014-05-11 10:15:08 | barb | saturn | 58274 |
| 2014-05-12 12:48:13 | tricia | mars | 194925 |
| 2014-05-12 15:02:49 | phil | mars | 1048 |
| 2014-05-12 18:59:18 | barb | saturn | 271 |
…
If you generate a column by evaluating an expression, the expression itself is the column
name. This can produce long and unwieldy names in result sets, as illustrated by the
following statement that uses one expression to reformat the dates in the
t
column, and
another to combine
srcuser
and
srchost
into email address format:
mysql>
SELECT
->
DATE_FORMAT(t,'%M %e, %Y'), CONCAT(srcuser,'@',srchost), size
->
FROM mail;
+----------------------------+-----------------------------+---------+
| DATE_FORMAT(t,'%M %e, %Y') | CONCAT(srcuser,'@',srchost) | size |
+----------------------------+-----------------------------+---------+
| May 11, 2014 | barb@saturn | 58274 |
| May 12, 2014 | tricia@mars | 194925 |
| May 12, 2014 | phil@mars | 1048 |
| May 12, 2014 | barb@saturn | 271 |
…
To choose your own output column name, use an
AS
name
clause to specify a column
alias (the keyword
AS
is optional). The following statement retrieves the same result as
the previous one, but renames the first column to
date_sent
and the second to
sender
:
mysql>
SELECT
->
DATE_FORMAT(t,'%M %e, %Y') AS date_sent,
->
CONCAT(srcuser,'@',srchost) AS sender,
->
size FROM mail;
+--------------+---------------+---------+
| date_sent | sender | size |
+--------------+---------------+---------+
| May 11, 2014 | barb@saturn | 58274 |
| May 12, 2014 | tricia@mars | 194925 |
| May 12, 2014 | phil@mars | 1048 |