SQL Aliases – Tutorial with Examples

SQL Aliases are used to give temporary names to columns or tables in a query. Aliases are useful when working with large and complex queries, as they make it easier to read and understand the results. In addition, they also allow you to modify the appearance of the column names in the result set, making them more user-friendly.

Syntax of SQL Aliases

SQL Aliases are created by using the “AS” keyword. The following is the general syntax for creating an alias in SQL:

SELECT column_name AS alias_name
FROM table_name;

Where “column_name” is the name of the column you want to create an alias for and “alias_name” is the temporary name you want to give to that column in the result set.

Examples of SQL Aliases

Consider the following “employees” table:

EmployeeID EmployeeName Salary Department
E001 John 5000 Marketing
E002 Jane 5500 Sales
E003 Bob 4500 IT
E004 Alice 4000 HR
E005 Eve 6000 Finance

Example 1: Creating an alias for a column

SELECT EmployeeName AS Employee, Salary
FROM employees;

The result of the above SQL statement will be:

Employee Salary
John 5000
Jane 5500
Bob 4500
Alice 4000
Eve 6000

In the above example, we have created an alias for the “EmployeeName” column and named it “Employee”. This makes it easier to understand and read the result set.

Example 2: Creating an alias for a table

SELECT e.EmployeeName AS Employee, e.Salary
FROM employees AS e;

The result of the above SQL statement will be:

Employee Salary
John 5000
Jane 5500
Bob 4500
Alice 4000
Eve 6000

In the above example, we have created an alias for the “employees” table and named it “e”. This makes it easier to reference the table in the query and avoids ambiguity if there are multiple tables with similar names in the database.

Conclusion

SQL Aliases are a useful tool for managing large and complex queries. By giving temporary names to columns and tables, you can make your queries more readable and user-friendly. Aliases also make it easier to reference columns and tables in your queries, especially when there are multiple columns or tables with similar names in the database.

Leave a Reply

Your email address will not be published. Required fields are marked *