
As in PostgreSql
AS
(Alias) in PostgreSQL
The AS
keyword in PostgreSQL is used to assign aliases to columns or tables, making query results more readable.
1. Aliasing a Column Name
SELECT salary AS total_salary FROM employees;
✅ The output column will be displayed as total_salary
instead of salary
.
2. Aliasing Multiple Columns
SELECT first_name AS fname, last_name AS lname FROM employees;
✅ The output columns will be fname
and lname
instead of first_name
and last_name
.
3. Using AS
in Calculations
SELECT SUM(salary) AS total_salary FROM employees;
✅ The result column will be named total_salary
.
4. Aliasing a Table Name
SELECT e.first_name, e.last_name FROM employees AS e;
✅ The alias e
is used instead of writing employees
each time.
5. Using AS
with JOIN
SELECT e.first_name, e.last_name, d.department_name FROM employees AS eJOIN departments AS d ON e.department_id = d.id;
✅ Aliases e
and d
make the query shorter and clearer.
6. Aliasing Subquery Columns
SELECT department, AVG(salary) AS avg_salaryFROM employeesGROUP BY department;
✅ The column name will be avg_salary
instead of AVG(salary)
.
Notes
- The
AS
keyword is optional in PostgreSQL for column aliases:SELECT first_name fname FROM employees;
- For table aliases,
AS
is not allowed, but you can still use an alias:SELECT e.first_name FROM employees e; -- ✅ WorksSELECT e.first_name FROM employees AS e; -- ❌ Error