Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql Comment Syntax - What's the difference between "#" and "-- "

According to the documentation, there are two ways you can comment to the end of a line in MySql:

  • "#"
  • "-- "

Is there any difference between these?

If so, when should I use one vs. the other?

If not, does anyone know why both are supported?

Seems strange to me, especially when the hyphenated version still differs slightly from the standard SQL Syntax.

like image 360
Jeremy Wiggins Avatar asked Jul 09 '13 17:07

Jeremy Wiggins


2 Answers

It only really matters if you want your SQL to be portable. For instance -- comments are OK in Sqlite and Postegresql while # are not. Your best bet is to use -- with a space following. (As far as I can remember I've hardly ever seen anything else)

like image 155
Sean Redmond Avatar answered Oct 26 '22 23:10

Sean Redmond


As the link you provided clearly explain it -- is the standard SQL "comment separator". Where MySQL departs from standard is in requiring an space after -- to be recognized as a comment. "Standard" SQL does not require this.

To provide an example, in the following code, -- is recognized as a comment token:

mysql> CREATE TABLE T(C int);   -- This is my new table
Query OK, 0 rows affected (0.18 sec)

But notice how the interactive interpreter misbehave without space after --:

mysql> CREATE TABLE T(C int);   --This is my new table
Query OK, 0 rows affected (0.24 sec)

    -> ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '--This is my new table' at line 1

MySQL support some other comment format to accommodate with habit of various programmers : # like many script language and /* ... */ like C. It is quite astounding that // is not yet part of them.

mysql> CREATE TABLE T(C int);   /* This is my new table */
Query OK, 0 rows affected (0.22 sec)

mysql> CREATE TABLE T(C int);   # This is my new table
Query OK, 0 rows affected (0.24 sec)
like image 41
Sylvain Leroux Avatar answered Oct 27 '22 01:10

Sylvain Leroux