# How to combine different columns of a table to yield a single column in query output in PostgreSQL?

PostgreSQLDatabaseData Storage

Suppose you have a table user_info that contains the state and district of different users. An example is given below −

namedistrictstate
AnilMumbaiMaharashtra
JoyJhalawarRajasthan
RonPuneMaharashtra

Now, if you want to combine the state and district in a single field called location, this is how you should be able to do it −

SELECT name, district || ', ' || state as location from user_info

The || operator is the string concatenation operator. The output will be −

namelocation
AnilMumbai, Maharashtra
JoyJhalawar, Rajasthan
RonPune, Maharashtra

Similar operations can also be performed on numerical values. Suppose you have a table marks containing the total marks scored by students and the maximum possible marks. An example is given below −

namemarks_scoredmax_marks
Anil342600
Joy567600
Ron456600
Reena543600

Now, if you wish to output a new column containing percentage marks, based on marks_scored and max_marks, you can do that as follows −

SELECT name, marks_scored*100.0/max_marks as perc from marks

The output will look like this −

nameperc
Anil57
Joy94.5
Ron76
Reena90.5

Published on 02-Feb-2021 13:02:21