4

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.

3
  • Hi @Marco can you provide the schema of your table? Commented Mar 22, 2019 at 10:43
  • 2
    Not sure what the difference between the two alternatives is, but you can also use psql -A -t to get rid of the column header and the (3 rows) feedback. Commented Mar 22, 2019 at 11:04
  • Thank you that's exactly what I want. The final command i have used is psql -A -t -d users -c \" select names from user \"" postgres Commented Mar 22, 2019 at 11:38

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

@a_horse_with_no_name These multiple edits are really AGGrevating for me :-(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.