how to export table to csv in mysql with headers code example

Example 1: mysql output csv

-- If you are using linux,

SELECT id, filename
FROM attachments
INTO OUTFILE '/tmp/results.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
-- and find the csv file /tmp

Example 2: mysql into outfile with headers

SELECT * FROM (
    SELECT 'username','email'
    UNION ALL
    (
        SELECT `username`,`email`,`steam_id` FROM `users` WHERE `userna` LIKE '%@temp%'
    )
) resulting_set
INTO OUTFILE '/results/result.txt' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n';

Tags:

Sql Example