PostgreSQL Table Aliases
Summary: in this tutorial, you will learn about the PostgreSQL table aliases and their practical applications.
Introduction to the PostgreSQL table aliases
A table alias is a feature in SQL that allows you to assign a temporary name to a table during the execution of a query.
The following illustrates the syntax of defining a table alias:
In this syntax:
table_name
: Specify the name of the table that you want to give an alias.alias_name
: Provide the alias for the table.
Like column aliases, the AS
keyword is optional, meaning that you can omit it like this:
PostgreSQL table alias examples
Let’s take some examples of using table aliases.
1) Basic PostgreSQL table alias example
The following example uses a table alias to retrieve five titles from the film
table:
Output:
In this example, we assign the film
table an alias f
and use the table alias to fully qualify the title
column.
Since the AS
keyword is optional, you can remove it as follows:
2) Using table aliases in join clauses
Typically, you use table aliases in a query that has a join clause to retrieve data from multiple related tables that share the same column name.
If you use the same column name that comes from multiple tables in the same query without fully qualifying them, you will get an error.
To avoid this error, you can qualify the columns using the following syntax:
If the table has an alias, you can qualify its column using the alias:
For example, the following query uses an INNER JOIN
clause to retrieve data from the customer
and payment
tables:
Output:
Note that you’ll learn about INNER JOIN in the upcoming tutorial.
3) Using table aliases in self-join
When you join a table to itself (a.k.a self-join), you need to use table aliases. This is because referencing the same table multiple times within a query will result in an error.
The following example shows how to reference the film
table twice in the same query using the table aliases:
Output:
Note that you’ll learn about self-join in the upcoming tutorial.
Summary
- Use PostgreSQL table aliases to assign a temporary name to a table during the execution of a query.