GBase 8a, the China-domestically developed MPP database from GBASE, exports query results to files with a customizable format. CSV is comma-separated and opens in Excel — but if the data contains newlines or double quotes, an untreated export produces shifted rows. Here is how to handle both in a gbase cluster.

The Source Data

Table t2 has 3 rows, and every name value contains newlines. Replacing them makes the structure visible:

gbase> select id,replace(name,'\n','\\n') from t2; +------+--------------------------+ | id | replace(name,'\n','\\n') | +------+--------------------------+ | 1 | 123\n456\n789 | | 2 | 2\n22\n222\n2222 | | 3 | 3\n33\n333\n3333 | +------+--------------------------+ 3 rows in set (Elapsed: 00:00:00.02) 

A Default Export Shifts Rows

gbase> select * from t2 into outfile '/home/gbase/t2_org.csv' fields terminated by ',' escaped by '' writemode by overwrites; Query OK, 3 rows affected (Elapsed: 00:00:00.07) 

One logical row is split into several physical lines by the embedded newlines:

[gbase@gbase_rh7_003 t2_org.csv]$ cat t2_org.csv 1,123 456 789 2,2 22 222 2222 3,3 33 333 3333 

Opened in Excel, the rows are misaligned.

Add a Double-Quote Enclosure

With enclosed by '"', Excel treats everything between two double quotes as one field, and the misalignment disappears:

gbase> select * from t2 into outfile '/home/gbase/t2.csv' fields terminated by ',' enclosed by '"' escaped by '' writemode by overwrites; Query OK, 3 rows affected (Elapsed: 00:00:00.05) 
[gbase@gbase_rh7_003 t2.csv]$ cat t2.csv "1","123 456 789" "2","2 22 222 2222" "3","3 33 333 3333" 

When the Data Itself Contains Double Quotes

A literal " inside a value now interferes with the enclosure. Two options:

  • Replace it with two double quotes using replace — more flexible.
  • Let DOUBLE_ENCLOSED BY '"' do it automatically — recommended, and simpler.
-- One option: replace by hand gbase> select id,replace(name,'"','""')name from t2; -- Another option, recommended: DOUBLE_ENCLOSED BY '"' gbase> select id,replace(name,'"','""')name from t2 into outfile '/home/gbase/t2_2.csv' fields terminated by ',' DOUBLE_ENCLOSED BY '"' enclosed by '"' escaped by '' writemode by overwrites; Query OK, 3 rows affected (Elapsed: 00:00:00.04) 
[gbase@gbase_rh7_003 t2_2.csv]$ cat t2_2.csv "1","123"" 456 789" "2","2 22 222 2222" "3","3 33 333 3333" 

Going forward, the enclosure keeps newline-bearing values as a single field, and doubling the inner quotes keeps them from breaking that enclosure. Stack the two and exports from the gbase database preserve the original content while still parsing cleanly in any spreadsheet tool.