DEV Community

Hamza Mushtaque
Hamza Mushtaque

Posted on

PostgreSQL Basics: Exploring Column Alias

In this tutorial, we will be exploring column alias and how to assign temporary names to different columns.

Introduction

Column aliases are used to assign temporary name to column or expression in SELECT statement. The whole purpose of aliases is to provide meaningful names to the outputs.
We use these aliases to also merge results from two different columns for creating more meaningful single columns.
For example: extracting first name and second name from table and then merging those results and giving them name as Full name using alias.

Basic Syntax

SELECT column_name AS alias_name
FROM table_name;
Enter fullscreen mode Exit fullscreen mode

alias_name is used instead of column_name in the result of above query.

**Note: **The AS is optional here. Hence, removing AS from the above query will provide similar result.

**Note: **For using alias with spaces in between, alias should be placed inside "". Following is an example demonstration.

SELECT column_name AS "alias name"
FROM table_name;
Enter fullscreen mode Exit fullscreen mode

Examples

Assume we have customer table and we run following query.

Code

SELECT first_name, last_name
FROM customer;
Enter fullscreen mode Exit fullscreen mode

Output
Table

Now assume, in our particular case, surname is more commonly used instead of last name.
Hence, we need to rename our column name as surname as it's more understandable in our region. This is where we could use Alias!

Code

SELECT first_name, last_name AS surname
FROM customer;
Enter fullscreen mode Exit fullscreen mode

Output

Table

As, you can see last name is changed to surname.

Now, we gonna look at the example where we combine fist name and last name as talked about earlier.

first, let's just combine them, later we gonna use alias to give it meaningful name.

Code

SELECT first_name || ' ' || last_name 
FROM customer;
Enter fullscreen mode Exit fullscreen mode

*Note: * || is an operator, used in postgreSQL to concatinate two or more strings.

Output

Table

As, you can see, we do have a required result but with no meaningful heading. Hence, now we would use Alias to give this expression meaningful name as full_name.

Code

SELECT first_name || ' ' || last_name AS full_name
FROM customer;
Enter fullscreen mode Exit fullscreen mode

Output

Table

Now, we will explore the use of "" in alias to give our result Full Name as Alias.

Code

SELECT first_name || ' ' || last_name AS "full name"
FROM customer;
Enter fullscreen mode Exit fullscreen mode

Output

Table

That's it for now!

Top comments (0)