Skip to main content

PostgreSQL Aliases

Introduction

When working with databases, you'll often encounter situations where table or column names are lengthy, complex, or not descriptive enough for your specific query. PostgreSQL aliases provide a solution by allowing you to assign temporary, alternative names to tables and columns within a query.

Aliases make your SQL code more readable, help avoid ambiguity when working with multiple tables, and simplify references to complex expressions. They exist only for the duration of the query and don't change the actual database structure.

Table Aliases

Basic Syntax

The basic syntax for creating a table alias is:

sql
SELECT column1, column2, ...
FROM table_name AS alias_name;

The keyword AS is optional in PostgreSQL, so you can also write:

sql
SELECT column1, column2, ...
FROM table_name alias_name;

Example: Simple Table Alias

Let's say we have a table called employee_data and want to use an alias to make our query more concise:

sql
SELECT e.employee_id, e.first_name, e.last_name
FROM employee_data AS e;

Output:

 employee_id | first_name | last_name
-------------+------------+-----------
1001 | John | Smith
1002 | Mary | Johnson
1003 | Robert | Williams

In this example, we've used e as an alias for the employee_data table, making our query shorter and easier to read.

Column Aliases

Basic Syntax

The syntax for creating a column alias is:

sql
SELECT column_name AS alias_name
FROM table_name;

Again, the AS keyword is optional:

sql
SELECT column_name alias_name
FROM table_name;

Example: Simple Column Alias

sql
SELECT first_name AS fname, last_name AS lname
FROM employee_data;

Output:

 fname  | lname
--------+-----------
John | Smith
Mary | Johnson
Robert | Williams

In this query, we've renamed first_name to fname and last_name to lname in the result set.

Example: Alias for Expressions

Aliases are particularly useful when working with expressions:

sql
SELECT 
product_name,
unit_price * units_in_stock AS inventory_value
FROM
products;

Output:

 product_name | inventory_value
--------------+-----------------
Chai | 648.00
Chang | 456.00
Aniseed Syrup| 100.00

Without the alias, the column header would be the entire expression unit_price * units_in_stock, which is less readable.

Using Aliases in Joins

Aliases are especially valuable when joining multiple tables, as they help clarify which columns come from which tables.

Example: Join with Aliases

sql
SELECT 
c.customer_name,
o.order_date,
o.order_amount
FROM
customers AS c
JOIN
orders AS o ON c.customer_id = o.customer_id;

Output:

 customer_name | order_date | order_amount
---------------+------------+--------------
ABC Company | 2023-01-15 | 1200.50
XYZ Corp | 2023-01-16 | 450.75
ABC Company | 2023-01-20 | 700.00

In this example, we've created aliases for both the customers and orders tables, making the join condition more concise and readable.

Using Aliases with Subqueries

Aliases are required when working with subqueries in the FROM clause.

Example: Subquery with Alias

sql
SELECT avg_price.average, p.product_name
FROM (
SELECT
category_id,
AVG(unit_price) AS average
FROM
products
GROUP BY
category_id
) AS avg_price
JOIN
products p ON p.category_id = avg_price.category_id
WHERE
p.unit_price > avg_price.average;

Output:

 average | product_name
---------+---------------
25.50 | Premium Tea
25.50 | Specialty Coffee
15.75 | Organic Honey

In this example, we've used an alias avg_price for the subquery that calculates the average price by category.

Best Practices for Using Aliases

  1. Use meaningful aliases: Choose names that reflect the data they represent, especially in complex queries.

  2. Be consistent: Establish a naming convention for your aliases and stick to it.

  3. Keep it concise: The purpose of aliases is to simplify; overly long aliases defeat this purpose.

  4. Always alias subqueries: Subqueries in the FROM clause must have an alias.

  5. Consider using aliases even for simple queries: This creates a consistent coding style and makes future modifications easier.

Alias Limitations

While aliases are powerful, they do have some limitations:

  1. Aliases defined in the SELECT clause cannot be used in the WHERE clause of the same query level (because WHERE is processed before SELECT).

  2. Aliases are valid only for the duration of the query.

  3. If an alias contains spaces or special characters, it must be enclosed in double quotes:

    sql
    SELECT product_name AS "Product Description"
    FROM products;

Practical Applications

Example 1: Reporting

When creating reports, aliases can transform technical column names into business-friendly terms:

sql
SELECT 
p.product_id,
p.product_name AS "Product",
c.category_name AS "Category",
p.unit_price AS "Unit Price",
p.units_in_stock AS "Stock",
p.unit_price * p.units_in_stock AS "Inventory Value"
FROM
products p
JOIN
categories c ON p.category_id = c.category_id
ORDER BY
"Inventory Value" DESC;

Example 2: Self Joins

Aliases are essential when a table joins to itself:

sql
SELECT 
e.employee_name AS "Employee",
m.employee_name AS "Manager"
FROM
employees e
LEFT JOIN
employees m ON e.manager_id = m.employee_id;

Output:

 Employee      | Manager
---------------+---------------
John Smith | Sarah Johnson
Mary Brown | Sarah Johnson
Robert Lee | John Smith
Sarah Johnson | NULL

In this self-join example, we're linking employees with their managers, both from the same table.

Summary

PostgreSQL aliases provide a powerful way to create temporary names for tables and columns within your queries. They improve readability, simplify complex queries, and make your SQL code more maintainable.

Key points to remember:

  • Table aliases help shorten references to tables
  • Column aliases rename columns in the result set
  • The AS keyword is optional but improves readability
  • Aliases are essential for joins and subqueries
  • Aliases exist only for the duration of the query

By mastering aliases, you'll write cleaner, more professional SQL code and build a solid foundation for more advanced PostgreSQL concepts.

Exercises

  1. Create a query that displays employee first and last names combined as "Full Name" using a column alias.

  2. Write a query joining the customers and orders tables using aliases, and display the customer name alongside their total order count.

  3. Create a query with a subquery that finds products priced higher than the average price in their category. Use appropriate aliases throughout.

Additional Resources

Remember that mastering aliases is an important step toward writing efficient and readable SQL queries. Practice regularly with different scenarios to become proficient.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)