Introduction
A comment is a remark from the programmer to explain things to other programmers or sometimes himself. Comments can be used to document the SQL statements to make them easier to understand. While parsing the SQL code, MySQL ignores the commented part and only executes the non-commented part.
Like in any other programming language comments are employed to enhance the readability of the code, same as MySQL provides comments to understand the written code in a better way.
So, Let’s get started now:
Source: Pinterest
MySQL Comment Styles
MySQL server mainly supports three comment styles.
- Using # symbol
- Using - symbol
- Using /* */ symbol
These can be used accordingly to make single or multi-line comments.
Using # Symbol
It is generally placed at the end of the line, and anything written after '# ' till end of the line falls in the scope of the comment. This comment style is generally used to put single-line comments.
Syntax:
SELECT statement; # Comment goes Here
Example
SELECT statement; # WHERE CMARKS >= 80
In the above example, the scope of the comment is from ‘#’ to the end of the line. And here, ‘WHERE CMARKS >= 80’ is not a part of the query and will be treated as a comment.
Using - - Symbol
The symbol - - is placed at the end of the line. And one must ensure that double -hyphen has at least one whitespace character or control character such as newline, tab or space, etc. However, there is no need for whitespace in standard SQL. MySQL uses whitespace to avoid the problems with some SQL statements, such as:
SELECT 100- - 5;
The statement will return 105. If MySQL didn’t use the whitespace, it would return 100 instead.
Syntax
SELECT statement; -- comment goes Here
Example
SELECT * FROM Student; -- WHERE CMARKS>=80
In the above example, the query is limited to the ‘;’ semicolon. Anything written after - - is only part of the text to explain things and will not be executed. This comment style is generally used to put single-line comments.
Using /* */ Symbol
This comment style can document a block of SQL code. Comments can span multiple lines. Moreover, anything written between /* and */ falls under the scope of comment.
Syntax:
/*
comment goes here
comment goes here
*/
Example
/*
This is the scope
Of multi-line
Comment.
*/
SELECT * FROM Student;
In the above example, the top three lines before the SQL command will be ignored during the execution process. Multiline comments are used for the large text descriptions of code or sometimes to comment out chunks of code while debugging.
Note: It is not always that comments must be multi-line or appear at the end. They can be a single-line and can come between SQL statements if needed. For example:
SELECT * /*comment*/ FROM Student;
here /*comment*/ is not a part of query.