Summary: in this tutorial, you will learn how to use MySQL comments to document your code in MySQL.
MySQL comments are essential for documenting your database schema, SQL queries, and stored procedures.
They help you and other developers understand the code and its purpose.
1) Single-Line Comments
Single-line comments are used to add comments on a single line.
MySQL supports two types of single-line comments:
Using --
You can add a single-line comment using two hyphens (--
) followed by your comment text. Any text following --
on the same line is treated as a comment. For example:
-- This is a single-line comment
SELECT * FROM employees;
Using #
Alternatively, you can use the hash (#
) symbol to add single-line comments. Any text following #
on the same line is treated as a comment. For example:
# This is another single-line comment
SELECT * FROM customers;
Code language: PHP (php)
2) Multi-Line Comments
Multi-line comments allow you to add comments spanning multiple lines. MySQL supports two types of multi-line comments:
Delimited by /* ... */
You can enclose your comments within /*
and */
to create multi-line comments. Everything between the opening /*
and closing */
is treated as a comment. For example:
/* This is a
multi-line comment */
SELECT * FROM orders;
Code language: JavaScript (javascript)
Using -- for Multi-Line Comments
While --
is primarily for single-line comments, you can use it for multi-line comments by adding --
at the beginning of each line. For example:
-- This is a multi-line comment
-- that spans multiple lines
SELECT * FROM products;
3) Executable comments
In MySQL, executable comments support portability between different databases. These comments allow you to embed SQL code that will execute only in MySQL but not in other databases.
The following illustrates the executable comment syntax:
/*! MySQL-specific code */
Code language: SQL (Structured Query Language) (sql)
For example, the following statement uses an executable comment:
SELECT 1 /*! +1 */
Code language: SQL (Structured Query Language) (sql)
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 */
Code language: SQL (Structured Query Language) (sql)
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,
KEY (k)
) /*!50110 KEY_BLOCK_SIZE=1024; */
Code language: SQL (Structured Query Language) (sql)
Summary
- Use comments to document your SQL statements, schemas, and stored procedures.