

The output in this example shows the value to be ‘/usr/files/’. To find out where the directories are, we can run either of these two commands: SELECT VARIABLES LIKE "secure_file_priv" Variable_name Add this directory path to our OUTFILE parameter so our file is generated there.Find out what the specific directories are.This essentially means that MySQL has a specific set of directories that can be used for input and output, and the file we’re attempting to write is not in that directory.

So you need to use a filename that does not exist.Īre you running this SELECT INTO OUTFILE and getting an error about “secure-file-priv”? So, what happens if you try this command and the file already exists?įor example, assuming the myoutput.txt file exists, you run this command: SELECT id, first_name, last_nameĮrror Code: 1086. So, it’s something you should test before you start using this as a permanent solution. This could mean the runtime is a lot slower. If you try to use a UNION or UNION ALL, the MySQL database may try to use a different execution plan to display the data, even though you’re only adding a single row.

This should ensure that your column headers are shown at the top. You could get around this by putting your main query in a subquery and then using UNION on that. This could mean that your column headers will end up at a place in the results that is not the top. This is because the ORDER BY clause goes at the end of the query, and will include your row of column headers in the ordering. If your query includes an ORDER BY clause, then your column headings won’t show correctly. All of the column headers are text values, so when the second part of the UNION query is run, it may try to add a date into a character column and cause an error. This is because the data type of the column is determined by the first query in the UNION. If you have any other types (such as numbers or dates) in your data, then you’ll get issues with your query. This only works if the data types are characters. However, there are a few issues with this: This would mean your column headings would be shown in the file: "id","first_name","last_name" So, your query would look like this: SELECT 'id', 'first_name', 'last_name' One commonly-mentioned way is to use a UNION ALL to select the column headings and the data. How can you get column headings to display? Unfortunately, there’s no easy option you can enable. You might have noticed that there are no column headings in the output file. You just add the INTO OUTFILE keyword to the end of a SELECT query and specify some parameters. So that’s how you can generate a CSV or text file in MySQL. The text in the file is: "1","John","Smith" If we run this statement, we can check the file, which will look like this:
