How to Comment in SQL
Database:
Operators:
Problem
You'd like to comment your code in SQL.
Example
Here's the example code:
SELECT name , COUNT (*) AS count_items FROM products GROUP BY name HAVING COUNT (*) > 5 ORDER BY name DESC ; |
Solution 1: Use -- to comment till the end of the line
Use --
to comment code till the end of the line. Here is what it looks like:
-- product names along with the number of items -- products ordered by name in descending order SELECT name , COUNT (*) -- AS count_items FROM products GROUP BY name -- HAVING COUNT(*) > 5 ORDER BY name DESC ; |
Discussion
You can write single-line comments in SQL using --
. After the --
, you can write any comment you'd like as long as it's in one line. If you'd like to write a comment spanning multiple lines, you can use --
at the beginning of each comment line, just as in the example:
-- product names along with the number of items -- products ordered by name in descending order |
You can also use --
to comment out a whole line of code or a part of a line from some place in the middle of the line to the end of the line. For example, you can comment out AS count_items
but leave the COUNT(*)
in.
COUNT (*) -- AS count_items |
Note that when you use --
you comment out the code to the end of the line, so you can’t use --
to comment out, for example, only the AS
keyword. If you want to do this, take a look at Solution 2.
Solution 2: Use /* ... */ for multiline comments
Use /*...*/
to comment code that spans multiple lines. Here is what it looks like:
/* product names along with the number of items this time, the products aren't sorted */ SELECT name , COUNT (*) /* AS */ count_items FROM products GROUP BY name /* HAVING COUNT(*) > 5 ORDER BY name DESC */ ; |
Discussion
/*...*/
is much more powerful than --
. With /*...*/
, you can comment out any part of the code you'd like. The comment can be multiline, and you can decide where it ends. Just write /*
at the beginning of the comment, and */
at the end.
For example, you can comment out a single word from the code, like the AS
keyword:
COUNT (*) /*AS*/ count_items |
Or you can comment out two lines but still leave the semicolon at the end:
/* HAVING COUNT(*) > 5 ORDER BY name DESC */ ; |