Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
ClausesStatementsKeywordsExpressionsFunctions

MySQL AS Keyword

The AS keyword in MySQL is used to assign an alias to a table or column, making it easier to reference or improving readability. It allows for temporary renaming within a query, which can simplify complex queries and result sets.

Usage

The AS keyword is typically used in SELECT statements to rename columns or tables in the result set. This improves clarity, especially when using expressions, functions, or when joining multiple tables. Note that AS is optional in MySQL, and an alias can be assigned without explicitly using it.

SELECT column_name AS alias_name
FROM table_name;

In this syntax, column_name AS alias_name assigns alias_name as a temporary name for column_name. Alternatively:

SELECT column_name alias_name
FROM table_name;

Examples

1. Basic Column Alias

SELECT first_name AS name
FROM employees;

In this example, the column first_name is renamed to name in the result set for clarity. Without AS:

SELECT first_name name
FROM employees;

2. Table Alias

SELECT e.first_name, e.last_name
FROM employees AS e;

Here, the table employees is given an alias e, which simplifies referencing its columns. Without AS:

SELECT e.first_name, e.last_name
FROM employees e;

3. Complex Expression Alias

SELECT CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;

This example uses the AS keyword to alias the result of a string concatenation as full_name, enhancing the readability of the output.

4. Aliasing in JOINs

SELECT o.order_id, c.customer_name
FROM orders o
JOIN customers c ON o.customer_id = c.id;

In this example, the tables orders and customers are aliased as o and c, respectively, which helps in making the JOIN operation clearer and more concise.

Tips and Best Practices

  • Use descriptive aliases. Choose meaningful alias names that clearly represent the data or operation.
  • Keep aliases concise. While being descriptive, keep aliases short to maintain query readability.
  • Consistent aliasing. Use the same alias consistently when referencing the same table or column across multiple queries.
  • Avoid reserved words. Do not use SQL reserved words as aliases to prevent syntax errors.
  • Enclose in quotes when necessary. Use backticks or quotes around aliases when they include spaces or special characters, e.g., SELECT column_name AS 'alias name'.