Summary: in this tutorial, you will learn how to use MySQL comment to document an SQL statement or a block of code in MySQL.
Comments can be used to document the purpose of an SQL statement or the logic of a code block in a stored procedure. When parsing SQL code, MySQL ignores the comments part. It only executes the SQL part except for executable comment, which we will discuss in the next section.
MySQL supports three comment styles:
- From a
'-- 'to the end of the line. The double dash-comment style requires at least whitespace or control character (space, tab, newline, etc) after the second dash.1SELECT * FROM users; -- This is a comment
Note that standard SQL does not require a whitespace after the second dash. MySQL uses a whitespace to avoid the problems with some SQL construct such as:1SELECT 10--1;
The statement returns 11. If MySQL didn’t use the whitespace, it would return 10 instead.
- From a
'#'to the end of the line.123456SELECTlastName, firstNameFROMemployeesWHEREreportsTo = 1002; # get subordinates of Diane
- C-style comment
/**/can span multiple lines. You use this comment style to document a block of SQL code.123456789101112/*Get sales rep employeesthat reports to Anthony*/SELECTlastName, firstNameFROMemployeesWHEREreportsTo = 1143AND jobTitle = 'Sales Rep';
Notice that MySQL does not support nested comments.
MySQL provides executable comments to support portability between different databases. These comments allow you to embed SQL code that will execute only in MySQL but not other databases.
The following illustrates the executable comment syntax:
/*! MySQL-specific code */
For example, the following statement uses an executable comment:
SELECT 1 /*! +1 */
The statement returns 2 instead of 1. However, it will return 1 if you execute it in other database systems.
If you want to execute a comment from a specific version of MySQL, you use the following syntax:
/*!##### MySQL-specific code */
The string ‘#####’ represents the minimum version of MySQL that can execute the comment. The first # is the major version e.g., 5 or 8. The second 2 numbers (##) are the minor version. And the last 2 is the patch level.
For example, the following comment is only executable in MySQL 5.1.10 or later:
CREATE TABLE t1 (
k INT AUTO_INCREMENT,
) /*!50110 KEY_BLOCK_SIZE=1024; */
In this tutorial, you have learned how to use MySQL comment to document the SQL code in MySQL.