Why joining the lines of a SQL query can break it, and what to remove first
Take a short query written over five lines. Line one is SELECT, then an optimizer hint /*+ INDEX(o idx_total) */, then name, and then a comment, -- who. Line two is total, lined up under name. Line three is FROM orders. Line four is WHERE total > 100, followed by the comment -- big ones. Line five is AND status = 'paid' with a space before the semicolon. With its alignment spaces, the query is 128 characters.
The quick way to get this on one line is to replace each line break with a space. Try it in your head. The first line ends with -- who, and a -- comment runs to the end of its line. After the join, the end of its line is the end of the query. The database now sees SELECT, the hint, name, and nothing more, because everything else is part of the comment. Depending on the database, you get a syntax error or a query that returns the wrong columns. This is the most common way a hand-minified query breaks.
So the minifier removes comments before it joins anything. Both -- who and -- big ones go. The hint does not, because a comment that starts with /*+ is an instruction to the query planner in Oracle and MySQL, and it changes how the query runs. Then the alignment spaces collapse to one space, the space before the semicolon goes, and the space after the comma goes too. The result is SELECT /*+ INDEX(o idx_total) */ name,total FROM orders WHERE total > 100 AND status = 'paid'; at 94 characters, about 27% shorter.
Some spaces cannot go, even where they look spare. In "total > 100", removing the spaces would be safe. In "a - -1", it would not: "a--1" starts a comment. In "SELECT name FROM", removing a space would merge two words. The minifier only removes spaces around commas, brackets and semicolons, where no two tokens can merge, and keeps one space everywhere else. That gives up a few bytes to make sure the query still means the same thing. The string 'paid' is copied as it is, and so is any space or line break inside a string.
Know the limits. The minifier does not check your SQL, so a broken query stays broken. It cannot bring back comments once removed, so keep the readable version if the comments explain anything. And a string that holds a line break keeps that line break, so the output is one line only when the strings in it are one line. For reading a minified query again, the SQL Formatter does the reverse.