Yogesh Chauhan's Blog

Column and Table Alias in Postgres

in Postgres on December 11, 2020

Whenever we want to give a temporary name to a table or a column, we can use alias and they are really helpful in many cases.

Column Alias

Syntax:


column_name AS alias_name //AS keyword is optional.

That’s it.

We don’t really need alias if we just want simple columns to be shown in the results. We only need in some cases like what if we concat two columns data? Then what will be the name for the result column?

For example, 


SELECT address || ', ' || city || ', ' || postal_code FROM customers;

//Output

?column?
"Obere Str. 57, Berlin, 12209"
"Avda. de la Constitución 2222, México D.F., 05021"
"Mataderos  2312, México D.F., 05023"
"120 Hanover Sq., London, WA1 1DP"
....
....
....

So, as we can  see in the query above, Postgres is confused to decide the column name as there are multiple columns in results concatenated.

So, to remove the confusion and to represent the data that makes sense we can just add column alias ‘Address’.

Lets look at the query results:


SELECT address || ', ' || city || ', ' || postal_code AS Address
FROM customers;

//Output

address
"Obere Str. 57, Berlin, 12209"
"Avda. de la Constitución 2222, México D.F., 05021"
"Mataderos  2312, México D.F., 05023"
....
....
....

As we can see in the query results above, now the column has a meaningful name.

Table Alias

Similar Syntax as column alias:


table_name AS alias_name //AS keyword is optional.

That’s it.

You’ve seen many times, the use of tables alias, especially in joins.

For example,


SELECT a.column, b.column FROM table a JOIN table b WHERE a.column = b.column;

Those are table alias.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Is there a way to do a FULL OUTER JOIN in MySQL?SQL/MySQLControl Scrolling with CSS Scroll SnapCSSHow to define visibility for a property in PHP?PHPSelf-Driving and Intelligent NetworksMiscellaneousHow to convert an HTML radio buttons into a toggle switch using CSS?CSSA quick introduction to API, REST API and PostmanMiscellaneous