What the SQL minifier removes
- Comments:
-- line comments,# comments(MySQL) and/* block comments */. You can keep them instead, and the tool then turns line comments into block comments, so that they cannot swallow the rest of the line. - Line breaks and indentation.
- Spaces around commas, parentheses and operators, wherever the query stays correct without them.
A single space is kept between two words, numbers or strings, because without it they would join into one token.
Example
-- paid orders per user
SELECT u.id,
u.name,
COUNT( o.id ) AS orders
FROM users u
LEFT JOIN orders o ON o.user_id = u.id /* only paid */ AND o.status = 'paid'
WHERE u.active = 1
GROUP BY u.id, u.name;
becomes:
SELECT u.id,u.name,COUNT(o.id) AS orders FROM users u LEFT JOIN orders o ON o.user_id=u.id AND o.status='paid' WHERE u.active=1 GROUP BY u.id,u.name;
What is never changed
- The text inside strings ('like this'), including spaces and line breaks.
- Quoted names in double quotes, backticks or brackets.
- MySQL version comments (
/*! ... */) and optimizer hints (/*+ ... */). They are read by the database, so they are always kept.
Why minify SQL?
- To embed a query in code or a config file as a single short string.
- To send a query in a URL, a header or an API field where line breaks are a problem.
- To make log lines shorter and easier to search with
grep. - To remove comments that you do not want to ship with an application.
Be honest about the benefit: a minified query does not run faster. The database parses a query in a very short time, and the difference between a formatted and a minified query is not measurable in practice. Minify for convenience and size, not for speed. If you need to read the query again later, keep the formatted version in your source files and minify only the copy that you ship.
Size, and gzip size
The tool shows the original size, the minified size, the percentage that you saved and, when your browser supports it, the size after gzip compression. Gzip already removes much of the repetition in white space, so the gain from minifying a query that is sent over the network compressed is small.
Options
Choose the dialect, so that comments and quoted names are read the way your database reads them. Choose whether keywords are kept as typed, written in uppercase or in lowercase. Remove comments or keep them. Put each statement on its own line or join them all.
To read minified SQL again, use the SQL beautifier or the SQL formatter. Other minifiers: CSS minifier, HTML minifier and JavaScript minifier. The SQL formatting guide explains when to use each.