Aliases

Aliases are nicknames. They give you a shorthand way of expressing a column, table, or function name, allowing you to:

  • Write shorter queries

  • Express your queries more clearly

  • Use one table in two or more ways in a single query

  • Access data more easily from programs (for example, from PHP scripts, as discussed in Chapter 14)

  • Use special types of nested queries; these are the subject of Nested Queries,” discussed later in this chapter

Column Aliases

Column aliases are useful for improving the expression of your queries, reducing the number of characters you need to type, and making it easier to work with languages such as PHP. Consider a simple, not-very-useful example:

mysql> SELECT artist_name AS artists FROM artist;
+---------------------------+
| artists                   |
+---------------------------+
| New Order                 |
| Nick Cave & The Bad Seeds |
| Miles Davis               |
| The Rolling Stones        |
| The Stone Roses           |
| Kylie Minogue             |
+---------------------------+
6 rows in set (0.00 sec)

The column artist_name is aliased as artists. You can see that in the output, the usual column heading, artist_name, is replaced by the alias artists. The advantage is that the alias artists might be more meaningful to users. Other than that, it’s not very useful, but it does illustrate the idea: for a column, you add the keyword AS and then a string that represents what you’d like the column to be known as.

Now let’s see column aliases doing something useful. Here’s an example that uses a MySQL function and an ORDER BY clause: ...

Get Learning MySQL 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.