Comments are one of the most important things in any programming language. With comments, you can explain what some parts of code do to other developers or to your future self. In this topic, we will talk about comments in SQL, their syntax, and their benefits.
What are the comments
In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program. They are added to make the source code easier for humans to understand, and are generally ignored by compilers and interpreters. Usually, there are explanations about code, details about the developer, or any juridical information.
The syntax of comments depends on the programming language's specificity. SQL also allows using the comments. Let's look at them.
Comments in SQL
SQL, like any programming language, has two types of comments, single-line and multi-line. Both of them have special syntax to separate comment text from other code.
For single-line comments use -- syntax. Any text between -- and the end of the line will be ignored (will not be executed):
-- Select all users from the table.
SELECT * FROM users;Multi-line comments start with /* and end with */. All text between that syntax will be ignored:
/* Select
all the records
from table users */
SELECT * FROM users;Yes, looks like comments are unnecessary here, we can easily understand what the query does without explanation. But it is just a simple example. In more difficult cases, comments are needed and should be used to make your code easier to understand by other people.
The good comment
Well, we've already talked about what comments should contain. But how to write a comment that will be pleasant to read?
Comments should be useful high-level descriptions of what the code is doing. They should not restate something obvious. Good comments should be clear, direct, and helpful. Also, if you want to write a long multi-line comment, you should divide it into paragraphs.
There're some examples of good:
/* Creates new product
in table Products
with 'ID', 'title' and 'price' columns */and bad commenting:
-- Creates new recordAlso, there's a practice of commenting part of some queries while debugging. It's fine, but be sure to delete commented code before production.
And remember: "If you can't write a clear comment, there may be a problem with the code."
Summary
Well, now you understand one of the most important things in any programming language philosophy – commenting. Many beginners don't comment on their code, but we strongly recommend doing it. Now let's repeat some key moments and move on to some tasks!
Use
--syntax to separate single-line comments.Use
/* */to separate multi-line comments.Good comment should be clear, direct, and helpful.