SQL Aliases
Aliases in SQL are used to give a table or a column in a table a temporary name. This name is often used to make the column or table names more readable or to simplify queries, especially when dealing with complex queries involving multiple tables and columns.
Column Aliases
A column alias is used to rename a column in the result set. This can be particularly useful for improving the readability of the output.
Syntax
SELECT column_name AS alias_name
FROM table_name;
Example
Suppose you have a table employees with the columns first_name, last_name, and salary. You want to concatenate first_name and last_name and display it as full_name in the result.
SELECT first_name || ' ' || last_name AS full_name, salary
FROM employees;
Use Cases
- Readability: Make complex expressions more understandable.
- Naming Conflicts: Resolve naming conflicts when joining tables with columns of the same name.
- Calculated Columns: Rename columns that result from calculations or functions for clarity.
Table Aliases
A table alias is used to rename a table within a query. This can make queries easier to write and read, especially when dealing with self-joins or complex queries involving multiple tables.
Syntax
SELECT column_name(s)
FROM table_name AS alias_name;
Example
Suppose you have two tables, orders and customers. You want to join these tables and simplify the query by using aliases.
SELECT o.order_id, c.customer_name
FROM orders AS o
JOIN customers AS c ON o.customer_id = c.customer_id;
Semantic portal
