Comments in SQL are basically texts that cannot be executed or they are ignored by the database engine. The role of comment is to provide a documentation or metainformation about a given query.
For example, let’s say you want to add a text to an SQL query that explains what the query does or what the requirements for that query are. This is what comments do: they enable you to add an information to the queries that you do not want to run in the database.
SQL comments are not executed as part of the SQL query and are completely ignored by the database engine.
Let us explore how we can define the comments in SQL.
Define the Comments in SQL
The way we define the comments in SQL depends on the type of comment that we wish to create. There are two types of comments in SQL:
The choice between either a single line or a multiline comment heavily depends on the comment context and mostly on the length of the comment that you wish to add.
Single-Line Comments
Single-line comments are some of the most common comment types in SQL. A common use case of a single line comment includes adding brief notes or disabling a specific query.
In SQL, we can create a single-line comment by adding two consecutive hyphens at the beginning of the line (–).
From there, any text that we add after the two hyphen characters is treated as a comment until the end of the line.
An example is as follows:
SELECT * FROM employees; -- another comment to explain the query
In this case, the text that follows the “–” character is treated as a comment.
Multi-Line Comments
Next, we have multi-line comments. Unlike the single-line comments, these types of comments can span multiple lines, making them very useful for creating an extensive and detailed documentation.
In SQL, we can create a multi-line starting with a backlash and asterisk character “/*”. We then add all the texts and information that we wish, spanning multiple lines. Once we are done, we close the comment with an asterisk and backslash character “*/”.
An example is as follows:
spanning multiple lines
to provide detailed information */
SELECT * FROM orders;
As you can see, the multi-line comments can span multiple lines without being executed by the SQL engine.
Conclusion
Comments in the world of development are essential tools for documenting and clarifying the SQL queries. In this tutorial, we learned how to create and use the single-line and multi-line comments.