MySQL uses SQL to work with databases. This guide will demonstrate how to write comments in MySQL statements.
Comments in MySQL
In MySQL, there are three types of commands available. They are separated by their symbols.
One important thing to remember is that MySQL doesn’t support nested comments.
Comment using “–“
By placing “–” at the end of a code line, you can place a single-line comment. Check out the following example.
$ SELECT * from employees; — End of line comment
Note that it doesn’t require having a space after the symbol “–” to write a comment. However, MySQL implements this feature to avoid problems with certain SQL queries. For example, this query would likely cause an issue with this type of commenting if there was no whitespace requirement.
$ SELECT 100–1; — Whitespace to not cause confusion
If MySQL didn’t require the whitespace, the result would be unexpected.
Comment using “#”
This is yet another type of comment that goes at the end of a line. It acts similar to the section demonstrated prior. For example,
$ SELECT * from employees; # end of line comment
If you ever had experience working with C programming, then you’ll be familiar with this type of comment. It starts with “/*” and ends with “*/”. Similar to C, the comments can span multiple lines.
Jumps over the lazy dog*/
SELECT * from users;
There’s another type of comment that MySQL supports – comments that will be executed. It’s an interesting feature that enhances the portability between different databases. It allows embedding codes that only MySQL will execute but not any other database solution.
An executable comment will generally look something like this. It involves C-style commenting. However, after “/*”, it starts with an exclamation (!) mark.
Let’s implement it in an executable code. In the following code, MySQL will return 5. However, any other database engine will return 10.
This commenting also supports specifying the version of MySQL required to run this code within the comment. In such a case, the comment structure will look something like this.
Note that there are 5 digits in total that describe the MySQL version.
- Character 1: Describes the major version, for example, 5 or 8.
- Character 2-3: Describes the minor version.
- Character 4-5: Describes the patch level.
In the following example, the comment code will only run if the MySQL server is v8.0.27.
To check the current version of MySQL, run the following command.
We can also get the MySQL version from the MySQL shell.
This guide describes all the supported formats of comments in MySQL. It also showcases their implementation within queries. In certain situations, MySQL even allows running code from the comments as well.