Mysql – How to get the result of MySQL explain query into a file

explainMySQL

I am unable to get the results of the explain query in its normal tabular format or json format into a file.

select * from table_name into outfile 'file.format';
select trace from information_schema.optimizer_trace into outfile 'file.json' lines terminated by '';

The above queries work, and I get the file. But the following queries do not create the file.

explain select * from table_name into outfile 'file.txt';
explain format=json select * from table_name into out 'file.json' lines terminated by '';

Is there any way to achieve this? It is preferable if the tabular explain results are written in text file with column names and table borders.

Best Answer

Using the syntax of EXPLAIN, no.

You can run the explain from the command line however:

mysql -e 'EXPLAIN ... ' > /tmp/myexplain.json

SQL isn't responsible for the pretty presentation of data, Workbench is one option.