AS
AS in SQL is used to assign an alias, or temporary name, to a table or a column in a query. This feature enhances readability and allows for more concise code. The assigned alias only exists for the duration of the query.
Example
SELECT firstname AS Name, age AS Age FROM users;
Output
Name | Age |
---|---|
Peter | 23 |
John | 30 |
Jane | 25 |
Explanation
In the given SQL query, “AS” is used to rename the columns in the output. The column “firstname” is displayed as “Name” and the column “age” as “Age”.
Example
CREATE TABLE Employees ( id INT PRIMARY KEY, name VARCHAR, salary FLOAT);
INSERT INTO EmployeesVALUES (1, 'John Doe', 50000), (2, 'Jane Smith', 60000), (3, 'Mike Johnson', 55000);
SELECT name AS Employee_Name, salary AS Employee_SalaryFROM Employees;
Output
| Employee_Name | Employee_Salary ||----------------|-----------------|| John Doe | 50000 || Jane Smith | 60000 || Mike Johnson | 55000 |
Explanation
In the given SQL code, a table named ‘Employees’ is created with three columns - ‘id’, ‘name’, and ‘salary’. Three rows are inserted into the table with different employee records. The ‘SELECT’ statement is then used with the ‘AS’ keyword to rename ‘name’ column as ‘Employee_Name’ and ‘salary’ column as ‘Employee_Salary’. The ‘AS’ keyword in SQL is used to rename a column or table with an alias. The output section shows the result of the select query.
Example
SELECT first_name AS NameFROM employee;
Output
Name-----JohnJaneKateSmith
Explanation
In this SQL statement, it selects a column “first_name” from the table “employee”. The “AS” keyword is used to rename the output header “first_name” to “Name”.
Example
SELECT first_name AS "Name", age AS "Age" FROM employees;
Output
Name | Age |
---|---|
John Doe | 30 |
Jane Doe | 25 |
Amanda Smith | 32 |
David James | 27 |
Explanation
In this example, the AS
keyword is used to rename the columns in the result set. The first_name
column is renamed to Name
and the age
column is renamed to Age
.
Example
CREATE TABLE Users ( ID INT PRIMARY KEY, Name TEXT, Age INT);
INSERT INTO Users (ID, Name, Age)VALUES (1, 'John Doe', 30), (2, 'Jane Doe', 25), (3, 'Roe Doe', 40);
SELECT Name AS 'User Name', Age AS 'User Age'FROM Users;
Output
| User Name | User Age ||-----------|----------|| John Doe | 30 || Jane Doe | 25 || Roe Doe | 40 |
Explanation
In SQL, the AS
keyword is primarily used to rename columns or tables with an alias. In the given example, the query renames the columns ‘Name’ and ‘Age’ as ‘User Name’ and ‘User Age’, respectively. The alias name is used to enhance query readability and results interpretation.