Export Vertica query result to csv file
Asked Answered
N

3

8

I`m working with Vertica. I try to export data from SELECT query into csv. I tried making it with sql query:

SELECT * FROM table_name INTO OUTFILE '/tmp/fileName.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

I got an error:

[Vertica][VJDBC](4856) ERROR: Syntax error at or near "INTO"

Is there a way to export a query result to a csv file? I prefer not to use vsql, but if there no other way, I will use it. I tried the following:

vsql -c "select * from table_name;" > /tmp/export_data.txt
Na answered 21/10, 2014 at 7:28 Comment(0)
C
12

Here is how you do it:

vsql -U dbadmin -F ',' -A -P footer=off -o dumpfile.txt -c "select ... from ... where ...;"

Reference: Exporting Data Using vsql

Clemen answered 5/11, 2015 at 21:4 Comment(2)
vsql -U dbadmin dwh -A -P footer=off -F ',' -c "SELECT 'Definitely not a valid csv, but who cares, right?' AS mycolumn;" | RESULT: | mycolumn Definitely not a valid csv, but who cares, right? Cytaster
How do I provide quote charater here. For example my output should be -> a,"hi,there",1Befitting
L
6

Accordingly to https://my.vertica.com/docs/7.1.x/HTML/Content/Authoring/ConnectingToHPVertica/vsql/ExportingDataUsingVsql.htm

=> SELECT * FROM my_table;
 a |   b   | c
---+-------+---
 a | one   | 1
 b | two   | 2
 c | three | 3
 d | four  | 4
 e | five  | 5
(5 rows)
=> \a
Output format is unaligned.
=> \t
Showing only tuples.
=> \pset fieldsep ','
Field separator is ",".
=> \o dumpfile.txt
=> select * from my_table;
=> \o
=> \! cat dumpfile.txt
a,one,1
b,two,2
c,three,3
d,four,4
e,five,5
Leland answered 27/2, 2017 at 18:46 Comment(2)
Thanks for it. I think => \pset fieldsep '\t' will be => \pset fieldsep ',' (according to response)Baerl
Does not handle case when data contains separator.Andreas
T
3

By following way you can write to CSV file as comma separated and no footer.

vsql -h $HOST -U $USER -d $DATABASE -w $PASSWORD -f $SQL_PATH/SQL_FILE -A -o $FILE -F ',' -P footer=off  -q  
Transgress answered 7/2, 2017 at 16:26 Comment(3)
+1 for footer=off, also - meta-command "-t --tuples-only disables printing of column names, result row count footers, and so on"Norward
Considering -o is used, -q seems unnecessary.Wont
Does not handle case when data contains separator.Andreas

© 2022 - 2024 — McMap. All rights reserved.