Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to combine different columns of a table to yield a single column in query output in PostgreSQL?
Suppose you have a table user_info that contains the state and district of different users. An example is given below −
| name | district | state |
|---|---|---|
| Anil | Mumbai | Maharashtra |
| Joy | Jhalawar | Rajasthan |
| Ron | Pune | Maharashtra |
| Reena | Meerut | Uttar Pradesh |
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 −
| name | location |
|---|---|
| Anil | Mumbai, Maharashtra |
| Joy | Jhalawar, Rajasthan |
| Ron | Pune, Maharashtra |
| Reena | Meerut, Uttar Pradesh |
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 −
| name | marks_scored | max_marks |
|---|---|---|
| Anil | 342 | 600 |
| Joy | 567 | 600 |
| Ron | 456 | 600 |
| Reena | 543 | 600 |
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 −
| name | perc |
|---|---|
| Anil | 57 |
| Joy | 94.5 |
| Ron | 76 |
| Reena | 90.5 |
Advertisements