SQL Tutorial
In SQL, AS
is a keyword that allows you to assign an alias or temporary name to a table or a column in a table. This can be particularly useful when you have long or complex column names, or when you want to give a more meaningful name to a derived column.
1. Column Alias
Column aliases are used to give a column in your result set a different name. This can be especially useful when the result of the query includes a derived column, such as a calculated value.
Syntax:
SELECT column_name AS alias_name FROM table_name;
Example:
SELECT COUNT(CustomerID) AS NumberOfCustomers FROM Customers;
In this example, the COUNT(CustomerID)
expression calculates the number of customers, and the AS
keyword is used to give it a more meaningful name in the result set.
2. Table Alias
Table aliases are used to give a table a shorter name, which can be particularly useful in more complex queries that involve joins of multiple tables, making the SQL statement more readable and concise.
Syntax:
SELECT column_name(s) FROM table_name AS alias_name;
Example:
SELECT c.CustomerName, o.OrderID FROM Customers AS c JOIN Orders AS o ON c.CustomerID = o.CustomerID;
In this example, the Customers
table is given the alias c
and the Orders
table is given the alias o
. This allows the JOIN
clause to be written more concisely.
Note: The AS
keyword is optional and can be omitted, but it often makes the SQL statement more readable.
Using AS for table aliases in SQL: Assign a short alias to a table for brevity and readability.
SELECT * FROM TableName AS T;
Creating field aliases with AS in SQL: Create aliases for fields to change their display names.
SELECT ColumnName AS AliasName FROM TableName;
SQL table alias in SELECT statement: Alias a table within the SELECT statement for easier reference.
SELECT T.ColumnName FROM TableName AS T;
Field aliasing in SQL queries: Assign aliases to fields for better readability and naming.
SELECT FirstName AS First, LastName AS Last FROM Employees;
AS keyword for column aliases in SQL: Use the AS keyword to define column aliases.
SELECT ProductName AS Name, Price AS Cost FROM Products;
Table and column aliases in JOIN operations: Alias tables and columns for concise JOIN conditions.
SELECT O.OrderID, C.CustomerName FROM Orders AS O JOIN Customers AS C ON O.CustomerID = C.CustomerID;
SQL AS vs equal sign for aliases: Both AS and the equal sign can be used for aliases; however, AS is more readable.
SELECT FirstName = 'John' FROM Employees; -- or SELECT FirstName AS 'John' FROM Employees;
Avoiding ambiguity with AS in SQL: Use aliases to avoid ambiguity, especially in self-joins.
SELECT E1.EmployeeID, E1.ManagerID, E2.EmployeeName FROM Employees AS E1 JOIN Employees AS E2 ON E1.ManagerID = E2.EmployeeID;