Skip to main content

VillageSQL is a drop-in replacement for MySQL with extensions.

All examples on this page work on VillageSQL. Install Now →
A result set takes its column headings from whatever you put in the select list. For a plain column that heading is the column name, which is usually fine. For a calculation it is the expression you typed, which is not. An alias replaces that heading with a name you choose. Open the client with mysql -u root -p sakila before you start.

How an alias works

Replace COLUMN_OR_EXPRESSION with the column or calculation you want, ALIAS_NAME with the heading you want it to have, and TABLE_NAME with the table. The alias applies to the result only. Nothing about the table changes, and the next query knows nothing about it.

Examples

1) Rename a column

The heading reads film_title. The values are untouched.

2) Name a calculation

This is where an alias earns its place. Without one the heading is the arithmetic.
Application code reads results by column name, so an unnamed expression leaves that code depending on the exact text of your arithmetic.

3) An alias containing a space

An alias made of letters, digits and underscores needs no quoting. Anything else does, including a space or a word MySQL has reserved for its own use, such as order or select. Backticks are the quoting style to reach for.
Single quotes produce the same heading:
They are not equivalent everywhere, though. Backticks mark a name, while single quotes mark a string, and a later clause that refers back to the alias can tell the difference. The next lesson shows that going wrong. Use backticks and the question never comes up. Leave the quotes off entirely and the server stops at the space:
ERROR 1064 is the general syntax error. The quoted fragment at the end of the message is where the server gave up, which is normally a word or two after the real mistake.

AS is optional, and leaving it out hides a typo

A bare name after a column means the same as AS. That is also how a forgotten comma disguises itself.
That was meant to be 2 columns. The missing comma turned release_year into an alias for title, so the result has 1 column, headed release_year, holding film titles. The server raised nothing, because the statement is valid. Writing AS on every alias does not make the server reject this, because neither column here has one. It does make the mistake visible when you read the query back: a bare name after a column, with no AS in front of it, is a missing comma.

Summary

  • Use AS to give a result column a name of your own.
  • Always alias a computed column, because its default heading is the expression.
  • Quote an alias with backticks when it contains a space or a reserved word.
  • Write AS on every alias, so a bare name reads as a missing comma.

See also