How can I check the SQL syntax in a .sql file?
TLDR:
>awk '{print "EXPLAIN " $0}' statements.sql | mysql --force -u user -p database | grep "ERROR"
Strangely, mysql does not have a built-in switch for this, but you can check syntax by adding the EXPLAIN
statement in front of your queries.
If you have a statements.sql
file with each statement on one line, prepend EXPLAIN
in front of all lines with:
>awk '{print "EXPLAIN " $0}' statements.sql > check.sql
You can then run the statements with the mysql
command-line tool and use --force
to have it continue on error. It will print an error for any statements with incorrect syntax.
>mysql --force -u user -p database < check.sql
Or to only view the lines with errors:
>mysql --force -u user -p database < check.sql | grep "ERROR"
You can do all of this on one line without creating an intermediate file:
>awk '{print "EXPLAIN " $0}' statements.sql | mysql --force -u user -p database | grep "ERROR"