Using Comments
As you have seen, SQL statements are instructions that are processed by your DBMS. But what if you wanted to include text that you’d not want processed and executed? Why would you ever want to do this? Here are a few reasons:
The SQL statements we’ve been using here are all very short and very simple. But, as your SQL statements grow (in length and complexity), you’ll want to include descriptive comments (for your own future reference or for whoever has to work on the project next). These comments need to be embedded in the SQL scripts, but they are obviously not intended for actual DBMS processing. (For an example of this, see the create.sql and populate.sql files used in Appendix B, “SQL Statement Syntax”).
The same is true for headers at the top of a SQL file (one that is saving SQL statements perhaps for future use), usually containing a description and notes, and perhaps even programmer contact information. (This use case is also seen in the Appendix B .sql files.).
Another important use for comments is to temporarily stop SQL code from being executed. If you were working with a long SQL statement, and wanted to test just part of it, you could comment out some of the code so that DBMS sees it as comments and ignores it.
Most DBMSs support several forms of comment syntax. We’ll start with inline comments:
Analysis ▾
Comments may be embedded inline using -- (two hyphens). Any text on the same line that is after the -- is considered comment text, making this a good option for describing columns in a CREATE TABLE statement, for example.
Here is another form of inline comment (although less commonly supported):
Analysis ▾
A # at the start of a line makes the entire line a comment. You can see this format comment used in the accompanying create.sql and populate.sql scripts.
You can also create multiline comments and comments that stop and start anywhere within the script:
Analysis ▾
/* starts a comment, and */ ends it. Anything between /* and */ is comment text. This type of comment is often used to comment out code, as seen in this example. Here, two SELECT statements are defined, but the first won’t execute because it has been commented out.