There are two primary ways to add comments in MySQL: single-line comments and multi-line comments.
1. Single-line Comments
In MySQL, single-line comments can be added in two ways:
Using -- Symbol
The comment must be followed by a space character. For example:
sql-- This is a single-line comment SELECT * FROM users;
Using # Symbol
This is another way to add single-line comments, and compared to double hyphens, using # is more concise. For example:
sql# This is a single-line comment SELECT * FROM users;
2. Multi-line Comments
Multi-line comments are used to comment out a block of code, which is very useful for explaining complex SQL statements or temporarily disabling parts of the code. Multi-line comments start with /* and end with */. For example:
sql/* This is a multi-line comment It can span multiple lines */ SELECT * FROM users;
Application Example
Suppose we are writing a complex query involving joining multiple tables and using multiple conditions; we might use comments to explain the purpose of each part:
sqlSELECT users.name, orders.order_date, products.name FROM users -- Joining users and orders tables INNER JOIN orders ON users.id = orders.user_id -- Joining orders and products tables INNER JOIN products ON orders.product_id = products.id WHERE orders.order_date > '2021-01-01' -- Selecting orders after 2021 ORDER BY orders.order_date;
The above covers the methods for adding comments in MySQL along with practical examples. Proper use of comments can significantly improve the readability and maintainability of SQL code.