MySQL – Output to CSV with Column Names at the Bottom

csvduplicationMySQL

I'm trying to export the results of the query listed below to csv and have the column names in the first row. However, when I run the code and open up the csv the header is listed as the last row. I have no idea why. What am I missing?

SELECT 'id','state','First_Name', 'Last_Name', 'Phone','County'
UNION ALL
SELECT id, state, First_Name, Last_Name, Phone, County
FROM tx.students
GROUP BY First_Name, Last_Name, Phone,
HAVING COUNT(*)>1
ORDER BY id
INTO OUTFILE '/var/lib/mysql-files/_students_dupes_test3.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

Best Answer

The records order is defined by your ORDER BY clause expression. All id field values are converted to string type due to the type of the base (first) subquery field type. Of course the digits are first and letters last.

Replace it with

ORDER BY id='id' DESC, id