SQL File Manipulation
This page describes various methods for extracting data from a database into a plain text format (e.g. CSV, JSON, XML etc) ingesting data into a database from a plain text format and manipulating data in a plain text file from within the database. The Database technologies where each method applies are shown by the buttons in the right hand column.
Extract
MySQL
INTO OUTFILE
Tab separated, newline terminated...
SELECT mycol1,mycol2,mycol3
  FROM mytable
  INTO OUTFILE '/tmp/myfile.txt';
Comma separated, newline terminated, each field enclosed in double quotes...
SELECT mycol1,mycol2,mycol3
  FROM mytable
  INTO OUTFILE '/tmp/myfile.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
Oracle
SPOOL
SET MARKUP csv ON DELIMITER ,
SPOOL myfile.csv
SELECT mycol1,mycol2,mycol3
  FROM mytable;
SPOOL OFF
SET COLSEP ,
SET PAGESIZE 0
SET TRIMSPOOL ON
SET HEADSEP OFF
SET LINESIZE 80
SET NUMW 10
SPOOL myfile.csv
SELECT mycol1,mycol2,mycol3
  FROM mytable;
SPOOL OFF
UTL_FILE
Microsoft SQL Server
PostgreSQL
In psql...
SELECT mycol1,mycol2,mycol3
FROM mytable \g /tmp/myfile.txt
To append to an existing file...
SELECT mycol1,mycol2,mycol3
FROM mytable \g | cat >>/tmp/myfile.txt
Alternate method in psql...
\o /tmp/myfile.txt
SELECT mycol1,mycol2,mycol3
FROM mytable;
\o
From shell...
echo 'SELECT mycol1,mycol2,mycol3 FROM mytable' | psql myDB >> /tmp/myfile.txt
Load
MySQL
Oracle
SQL*Loader
UTL_FILE
SQL Developer
Microsoft SQL Server
PostgreSQL
Transform
MySQL
Oracle
Microsoft SQL Server
PostgreSQL
Bibliography
PostgreSQLhttps://www.postgresql.org/message-id/15392.46537.511719.871128%40elsick.csl.co.ukhttps://stackoverflow.com/questions/5331320/psql-save-results-of-command-to-a-filehttps://dba.stackexchange.com/questions/251507/is-it-possible-to-write-a-function-in-postgresql-which-directly-writes-its-param
RDS PostgreSQL to S3https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/postgresql-s3-export.html
Oraclehttps://stackoverflow.com/questions/643137/how-do-i-spool-to-a-csv-formatted-file-using-sqlplus