Aliasing Attributes

tags: #sql

What is aliasing?

Alias in SQL is used to give a table or column a temporary name for the duration of a SQL query. It is also known as renaming. This is accomplished using the AS keyword.

Why do we do this?

Alias is useful when:

Aliasing Syntax

Tables (Relations)

The general syntax for aliasing a table is as follows:

SELECT column_name(s)
FROM table_name AS alias_name;

-- or

SELECT column_name(s)
FROM table_name alias_name;

We can also give alternative aliases to the same relation TWICE in a query. This can be useful in cases where you need to join a table to itself, or perform multiple operations on the same table within a single query.

// example
SELECT e.emp_name AS employee_name, s.emp_name AS supervisor_name
FROM employees e
INNER JOIN employees s ON e.supervisor_id = s.emp_id;

In this example, the employees table is used twice in the query to find the names of employees and their supervisors. The e and s aliases are used to qualify the attribute names with the relation names, so that the query can distinguish between the different occurrences of the same table.

Columns (Attributes)

The general syntax for aliasing an attribute is as follows:

SELECT column_name AS alias_name
FROM table_name;
Powered by Forestry.md