totn SQL

SQL: Comments

This SQL tutorial explains how to use comments within your SQL statements with syntax and examples.

Description

In SQL, you can comment your code just like any other language. Comments can appear on a single line or span across multiple lines. Let's explore how to comment your SQL statements.

Syntax

There are two syntaxes that you can use to create a comment in SQL.

Syntax Using -- symbol

The syntax for creating a comment in SQL using -- symbol is:

-- comment goes here

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 /* and */ symbols

The syntax for creating a comment in SQL using /* and */ symbols is:

/* comment goes here */

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

Let's look at an example that shows how to create a comment in SQL that is on a single line.

For example:

Here is a comment that appears on its own line in SQL:

SELECT websites.site_name
/* Author: TechOnTheNet.com */
FROM websites;

Here is a comment that appears in the middle of the line in SQL:

SELECT  /* Author: TechOnTheNet.com */  websites.site_name
FROM websites;

Here is a comment that appears at the end of the line in SQL:

SELECT websites.site_name  /* Author: TechOnTheNet.com */
FROM websites;

or

SELECT websites.site_name  -- Author: TechOnTheNet.com
FROM websites;

Example - Comment on Multiple Lines

You can also create a comment that spans multiple lines in your SQL statement.

For example:

SELECT websites.site_name
/*
 * Author: TechOnTheNet.com
 * Purpose: To show a comment that spans multiple lines in your SQL statement.
 */
FROM websites;

This comment spans across multiple lines in SQL and in this example, it spans across 4 lines.

You can also create a comment that spans multiple lines using this syntax:

SELECT websites.site_name /* Author: TechOnTheNet.com
Purpose: To show a comment that spans multiple lines in your SQL statement. */
FROM websites;

SQL 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 comment will span across 2 lines.