SQL Aliases are used to give a temporary name to a table or a column in a SQL query. It is a way to make the SQL query more readable and understandable. Aliases are commonly used in complex SQL queries where tables or columns have long or complicated names.
Aliases are created using the AS keyword in the SELECT statement. The AS keyword is optional, and aliases can be created without it. However, it is recommended to use the AS keyword for better readability.
Aliases can be used for tables, columns, and even for subqueries. In this tutorial, we will discuss how to use aliases for tables and columns.
Aliases for tables are used to give a temporary name to a table in a SQL query. This is useful when we need to join multiple tables in a query, and the table names are long or complicated.
Let's consider the following example:
SELECT orders.order_id, customers.customer_name FROM orders INNER JOIN customers ON orders.customer_id = customers.customer_id;
In this query, we are joining the orders and customers tables using the customer_id column. The result of this query will have two columns: order_id and customer_name.
We can use aliases to make this query more readable:
SELECT o.order_id, c.customer_name FROM orders AS o INNER JOIN customers AS c ON o.customer_id = c.customer_id;
In this query, we have given the orders table an alias of "o" and the customers table an alias of "c". We have then used these aliases to refer to the columns in the SELECT and JOIN statements.
Aliases for columns are used to give a temporary name to a column in a SQL query. This is useful when we need to perform calculations or transformations on a column, and we want to give the result a meaningful name.
Let's consider the following example:
SELECT customer_name, order_date, order_total FROM customers INNER JOIN orders ON customers.customer_id = orders.customer_id;
In this query, we are selecting the customer_name, order_date, and order_total columns from the customers and orders tables. The result of this query will have three columns with the same names as the selected columns.
We can use aliases to give these columns more meaningful names:
SELECT customer_name, order_date AS date, order_total AS total FROM customers INNER JOIN orders ON customers.customer_id = orders.customer_id;
In this query, we have given the order_date column an alias of "date" and the order_total column an alias of "total". We have then used these aliases to refer to the columns in the SELECT statement.
SQL Aliases are a powerful tool for making SQL queries more readable and understandable. They can be used for tables, columns, and even for subqueries. Aliases are created using the AS keyword in the SELECT statement, and they are optional but recommended for better readability.