A comment is a note for humans. MySQL ignores it.
Three comment styles
-- This is a comment. Note the space after the two dashes.
SELECT 1 AS one; -- A comment can also follow a statement.
# MySQL also accepts a hash sign for a one-line comment.
SELECT 2 AS two;
/* This comment can
span several lines. */
SELECT /* or sit inside a statement */ 3 AS three;
+-----+
| one |
+-----+
| 1 |
+-----+
1 row in set
+-----+
| two |
+-----+
| 2 |
+-----+
1 row in set
+-------+
| three |
+-------+
| 3 |
+-------+
1 row in set
| Style | Where it works | Notes |
|---|---|---|
-- text | Standard SQL and MySQL | Needs a space (or control character) after -- |
# text | MySQL only | Not portable |
/* text */ | Standard SQL and MySQL | Can span lines. Cannot be nested |
The space after --
In MySQL, -- starts a comment only if it is followed by a space, a tab or a new line. This protects expressions such as 5--3:
SELECT 5--3 AS result;
+--------+
| result |
+--------+
| 8 |
+--------+
1 row in set
MySQL read that as 5 - (-3), which is 8. Without the rule, it would have treated --3 as a comment and returned 5. When you write comments, always put a space after --.
Good uses of comments
- Explain why a query is written the way it is, not what each word does.
- Mark a section of a long script.
- Temporarily switch off a line while you debug.
-- Only active customers; inactive ones are archived monthly.
SELECT 'ok' AS note;
+------+
| note |
+------+
| ok |
+------+
1 row in set
Executable comments (MySQL-specific)
MySQL gives a special meaning to a block comment that starts with /*!. The server runs what is inside it, while other databases treat it as a normal comment:
SELECT 1 /*!50001 + 10 */ AS runs_on_5_0_1_or_newer, 1 /*!99999 + 10 */ AS needs_version_9_99_99;
+------------------------+-----------------------+
| runs_on_5_0_1_or_newer | needs_version_9_99_99 |
+------------------------+-----------------------+
| 11 | 1 |
+------------------------+-----------------------+
1 row in set
The number is a version: 50001 means 5.0.1, and 80000 means 8.0.0. You will see this in files made by mysqldump, so that a dump can include MySQL-specific commands without breaking other tools. You rarely need to write one yourself.
Optimizer hints
A comment that starts with /+ is an optimizer hint, an instruction to the query planner. For example SELECT /+ MAX_EXECUTION_TIME(1000) */ ... stops a query after one second. A comment-style hint is ignored by other databases. See Optimizer Hints.