Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only the data when i execute a query in PostgreSQL

When I execute my query in PostgreSQL:

SELECT names 
from user;

I obtain the following result:

      names
--------------
Anna
Julius
Perico

(3 rows)

What I want to get is the following output:

Anna Julius Perico

I need this because is a bash script ant I need to save it in a variable.

like image 309
Marco Avatar asked Sep 12 '25 03:09

Marco


2 Answers

If you want to use it in a shell script, this would be the best way:

myvar=`psql --no-align --quiet --tuples-only --command='SELECT name FROM users'`

No need to have them in one line; the shell accepts a line feed as field separator as well:

for n in $myvar; do
    echo "name: $n"
done

name: Anna
name: Julius
name: Perico
like image 137
Laurenz Albe Avatar answered Sep 14 '25 18:09

Laurenz Albe


The string_agg function might be what you want here:

select string_agg(names, ' ' order by names) from user;

I said "might" because this assumes that the names column itself could be used to generate the order in the single string output. If you want a different order, then you would need another column.

like image 45
Tim Biegeleisen Avatar answered Sep 14 '25 17:09

Tim Biegeleisen