SQL Tutorial
SQL Clauses / Operators
SQL-Injection
SQL Functions
SQL Queries
PL/SQL
MySQL
SQL Server
Misc
In SQL, an alias is a temporary name given to a table or a column for the purpose of a specific SQL query. Aliases can be useful for several reasons:
You can assign an alias to a column using the AS
keyword, although the AS
keyword is optional in many databases.
SELECT first_name AS fname, last_name AS lname FROM employees;
In this example, the columns first_name
and last_name
are aliased as fname
and lname
, respectively.
Aliases are particularly useful when you're working with joins and you want to reference columns from specific tables.
SELECT e.fname, e.lname, d.name AS department_name FROM employees AS e JOIN departments AS d ON e.department_id = d.id;
In the example above, the employees
table is aliased as e
and the departments
table as d
. This allows for more concise column referencing, especially in the context of joins.
AS
keyword; it's often optional.How to use aliases in SQL:
SELECT column1 AS alias_name FROM your_table;
Column aliases in SELECT statements:
SELECT column1 AS alias_name FROM your_table;
Table aliases in SQL queries:
SELECT t.column1 FROM your_table t;
Using aliases with aggregate functions:
SELECT AVG(column1) AS avg_value FROM your_table;
Aliases and ORDER BY in SQL:
SELECT column1 AS alias_name FROM your_table ORDER BY alias_name;
Aliases with expressions and calculations:
SELECT column1 * 2 AS double_value FROM your_table;
Aliases in JOIN operations in SQL:
SELECT t1.column1, t2.column2 FROM table1 t1 JOIN table2 t2 ON t1.id = t2.id;
Aliases for subqueries in SQL:
SELECT column1 FROM (SELECT column1 FROM your_table) AS subquery_alias;
Aliases vs. table or column names in SQL:
SELECT column1 AS alias_name, column2 FROM your_table;
Aliases in WHERE and HAVING clauses:
SELECT column1 AS alias_name FROM your_table WHERE alias_name > 10;
Nested aliases in SQL:
SELECT (SELECT AVG(column1) FROM your_table) AS avg_value FROM another_table;
Aliases and self-joins in SQL:
SELECT e1.employee_name, e2.manager_name FROM employees e1 JOIN employees e2 ON e1.manager_id = e2.employee_id;
Aliases and calculated columns in SQL:
SELECT column1 * column2 AS product FROM your_table;