We can use the MySQL outfile statement to save the query output into a file. This is very useful when the query result is huge and you want to analyze it by exporting it into a file.

MySQL outfile statement syntax

The outfile syntax is very simple. It should be the last part of the SQL query.

The SQL query output will be saved to the file in the text format.

Saving MySQL Query Output to File

Let’s look at some examples to save the MySQL query output to a file.

The output is getting redirected to the file. It’s not being printed on the MySQL console.

If you open the file, you will see the SQL query data is saved as tab-separated.

Let’s run another query that produces small output and compare the console output with the file contents.

File Content:

mysql-query-output-to-file-content

Mysql Query Output To File Content

Error Scenarios

The MySQL user should have permissions to create the file at the specified path.

If the file is already present, then the MySQL query will not rewrite or append to it. It will simply throw error as file is already present.

By admin

Leave a Reply

%d bloggers like this: