Aliases

Temporary names.

Introduction

Aliases are temporary names assigned to a table or column for the duration of a query. They make queries easier to read, especially when dealing with complex queries, or when the table or column names are lengthy.

Why Use Aliases?

  • Improves Readability: Aliases simplify complex queries by giving shorter, more intuitive names to tables or columns.
  • Handling Name Conflicts: In cases where column names from different tables conflict (such as in JOINs), aliases help differentiate them.
  • Ease of Use in Self Joins: When you need to join a table with itself (self join), using aliases can prevent confusion.
  1. Column Alias A column alias renames a column heading in the result set. Useful for renaming a column to something more user-friendly or descriptive.

Syntax:

SELECT column_name AS alias_name
FROM table_name;

Table

Customers

SQL logo

Example

SELECT first_name AS 'First Name', last_name AS 'Last Name'
FROM Customers;

In this example, first_name is renamed to 'First Name', and last_name is renamed to 'Last Name' in the query result.

Where
  1. Table Alias A table alias provides a temporary name for a table. It’s particularly useful when joining multiple tables or referring to a table multiple times in a query.

Syntax:

SELECT alias_name.column_name
FROM table_name AS alias_name;

Example:

SELECT c.first_name
FROM Customers AS c

In this case, Customers table is aliased as c making the query easier to read.

Points to Remember:

  • Aliases are not permanent; they only last for the duration of the query.
  • The AS keyword is optional for aliases in most databases but improves readability.
  • Aliases are particularly helpful in self-joins and complex queries involving multiple tables or subqueries.

Conclusion

Aliases in MS SQL are a powerful tool to simplify your queries, enhance readability, and manage complex operations such as joins and subqueries. While they are temporary, their proper use can make your SQL queries more efficient, organized, and easier to maintain.