SQL комментарии
В этом учебном материале вы узнаете, как использовать комментарии в выражениях SQL с синтаксисом и примерами.
Описание
В SQL вы можете комментировать свой код, как и любой другой язык. Комментарии могут появляться в одной строке или занимать несколько строк. Давайте рассмотрим, как комментировать ваши операторы SQL.
Синтаксис
Есть два синтаксиса, которые вы можете использовать для создания комментария в SQL.
Синтаксис использования символов — (два тире)
Синтаксис для создания комментария в SQL с использованием символов — .
— здесь пишется комментарий
Комментарий, начинающийся с символов — , должен находиться в конце строки в вашем операторе SQL с разрывом строки после него. Этот метод комментирования может занимать только одну строку в вашем SQL и должен находиться в конце строки.
Синтаксис использования символов /* и */
Синтаксис для создания комментария в SQL с использованием символов /* и */ .
/* здесь пишется комментарий */
Комментарий, который начинается с символа /* и заканчивается */ и может находиться в любом месте вашего SQL оператора. Этот метод комментирования может занимать несколько строк в вашем SQL.
Пример комментария в одной строку
Рассмотрим пример комментария в SQL, который находится на одной строке.
Например.
Вот комментарий, который появляется в SQL в отдельной строке.
MySQL: Comments within SQL
This MySQL tutorial explains how to use comments within your SQL statements in MySQL with syntax and examples.
Description
Did you know that you can place comments within your SQL statements in MySQL? These comments can appear on a single line or span across multiple lines. Let’s look at how to do this.
Syntax
There are three syntaxes that you can use to create a comment within your SQL statement in MySQL.
Syntax Using # symbol
The syntax for creating a SQL comment in MySQL using # symbol is:
In MySQL, a comment started with # symbol must be at the end of a line in your SQL statement with a line break after it. This method of commenting can only span a single line within your SQL and must be at the end of the line.
Syntax Using — symbol
The syntax for creating a SQL comment in MySQL using — symbol is:
In MySQL, a comment started with — symbol is similar to a comment starting with # symbol. When using the — symbol, the comment must be at the end of a line in your SQL statement with a line break after it. This method of commenting can only span a single line within your SQL and must be at the end of the line.
Syntax Using /* and */ symbols
The syntax for creating a SQL comment in MySQL using /* and */ symbols is:
In MySQL, a comment that starts with /* symbol and ends with */ and can be anywhere in your SQL statement. This method of commenting can span several lines within your SQL.
Example — Comment on a Single Line
You can create a SQL comment on a single line in your SQL statement in MySQL.
Let’s look at a SQL comment example that shows a SQL comment that is on a single line and does not span multiple lines.
Here is a SQL comment that appears in the middle of the line:
Here is a SQL comment that appears at the end of the line:
Example — Comment on Multiple Lines
In MySQL, you can create a SQL comment that spans multiple lines in your SQL statement. For example:
This SQL comment spans across multiple lines in MySQL — in this example, it spans across 5 lines.
In MySQL, you can also create a SQL comment that spans multiple lines using this syntax:
MySQL will assume that everything after the /* symbol is a comment until it reaches the */ symbol, even if it spans multiple lines within the SQL statement. So in this example, the SQL comment will span across 2 lines within the SQL statement.
How to give comments in SQL
I am working in SQL. What is the complete explanation for using comments in SQL, with some example code?
![]()
![]()
5 Answers 5
MySQL Server supports three comment styles:
From a # character to the end of the line.
From a — sequence to the end of the line. In MySQL, the “— ” (double-dash) comment style requires the second dash to be followed by at least one whitespace or control character (such as a space, tab, newline, and so on). This syntax differs slightly from standard SQL comment syntax, as discussed in Section 1.8.2.5, “’—‘ as the Start of a Comment”.
From a /* sequence to the following */ sequence, as in the C programming language. This syntax enables a comment to extend over multiple lines because the beginning and closing sequences need not be on the same line.
In Oracle, there are three ways.
1.
2.
3.
The difference between REM and the other two is that, — and /* */ can be used in a PL/SQL block, while REM[ARK] cannot.
So, — and /* */ works in PL/SQL block too. However, REM won’t.
Update Mostly all GUI based tools are able to execute SQL*Plus commands in their own sqlplus type window. It works perfectly in SQL Developer when executed as a script . In PL/SQL Developer too it should work with COMMAND window.
A screenshot from SQL Developer .

Same in SQL*Plus .
You can write a comment in SQL & PLSQL statements in two easy ways:
Begin the comment section with a forward slash and an asterisk (/*). Proceed with the text of the comment. This text can be spanning multiple lines.
Begin the comment section with — (two hyphens). Proceed with the text of the comment. This text cannot extend to a new line for new commenting. Every line start with – (two hyphens). Let see below examples
SELECT e.ename /* Author: OnlinteItTutor.com */ FROM emp e;
Here is a SQL comment in query that appears in the middle of the line:
Here is a SQL comments in query that appears at the end of the line:
In Oracle, you can create a SQL comment that shows multiple lines in your SQL statement. For example:
This SQL comment in query shows across multiple lines in Oracle — in this example, it shows across 4 lines. In Oracle, you can also create a SQL comment in query that spans multiple lines using this syntax:
Как сделать комментарий в sql
Сервер MySQL поддерживает следующие способы задания комментариев: с помощью символа `#’ , за которым следует текст комментария до конца строки; с помощью двух символов — , за которыми идет текст комментария до конца строки; и (для многострочных комментариев) с помощью символов /* (начало комментария) и */ (конец комментария):
Обратите внимание: при использовании для комментирования способа с — (двойное тире) требуется наличие хотя бы одного пробела после второго тире!
Хотя сервер «понимает» все описанные выше варианты комментирования, существует ряд ограничений на способ синтаксического анализа комментариев вида /* . */ клиентом mysql :
- Символы одинарной и двойной кавычек, даже внутри комментария, считаются началом заключенной в кавычки строки. Если внутри комментария не встречается вторая такая же кавычка, синтаксический анализатор не считает комментарий законченным. При работе с mysql в интерактивном режиме эта ошибка проявится в том, что окно запроса изменит свое состояние с mysql> на ‘> или «> .
- Точка с запятой используется для обозначения окончания данной SQL-команды и что-либо, следующее за этим символом, указывает на начало следующего выражения.
Эти ограничения относятся как к интерактивному режиму работы mysql (из командной строки), так и к вызову команд из файла, читаемого с ввода командой mysql < some-file .
MySQL поддерживает принятый в ANSI SQL способ комментирования с помощью двойного тире `—‘ только в том случае, если после второго тире следует пробел (see section 1.9.4.7 Символы `—‘ как начало комментария).