How to Add Comments in MySQL

08/03/2021

Contents

In this article, you will learn how to add comments in MySQL.

Adding comments in MySQL

Comments in MySQL are used to add descriptive text to SQL statements or objects within the database. They can be used to explain the purpose of a statement, provide instructions to other developers, or leave notes to remind yourself of something important. Here’s how to add comments in MySQL:

Using single-line comments

Single-line comments begin with two dashes “–“. Any text that follows these dashes on the same line is treated as a comment and is ignored by MySQL.

-- This is a single-line comment in MySQL
SELECT * FROM my_table; -- This is another single-line comment

Using multi-line comments

Multi-line comments begin with “/” and end with “/”. Any text between these two markers is treated as a comment and is ignored by MySQL.

/* This is a
multi-line comment in MySQL */
SELECT * FROM my_table; /* This is another
multi-line comment */

Adding comments to objects

You can also add comments to objects within the database, such as tables, columns, or stored procedures. To add a comment to a table or a column, use the COMMENT keyword followed by the comment text.

CREATE TABLE my_table (
   id INT COMMENT 'This is the primary key',
   name VARCHAR(50) COMMENT 'This is the name of the user'
) COMMENT 'This is a table for storing user information';

In the above example, we added comments to the table my_table, as well as to its columns id and name.

To add a comment to a stored procedure or a function, use the COMMENT keyword followed by the comment text after the END keyword.

CREATE PROCEDURE my_procedure()
BEGIN
   -- procedure logic
END /* This is a comment for the stored procedure */;

In the above example, we added a comment to the stored procedure my_procedure.

Viewing comments

To view comments associated with a table or a column, you can use the SHOW CREATE TABLE statement.

SHOW CREATE TABLE my_table;

This will display the SQL statement used to create the table, along with any comments added to the table or its columns.

To view comments associated with a stored procedure or a function, you can use the SHOW CREATE PROCEDURE or SHOW CREATE FUNCTION statement.

SHOW CREATE PROCEDURE my_procedure;

This will display the SQL statement used to create the stored procedure, along with any comments added to it.