SQL Comments

SQL Comments explain sections of SQL statements or prevent SQL statements from being executed.

There are 3 types of comments in SQL:

  1. Single-line comments
  2. Multi-line comments
  3. In-line comments

These are the three commenting methods in SQL, each with its unique use. Let’s discuss these SQL comments in detail below:

SQL Single Line Comments

SQL Single Line Comments contain a single line a comment. They start and end in a single line.

Single Line comments in SQL can be inserted using ‘–‘ before the line. 

Syntax:

Syntax to insert single line comment in SQL is:

— single line comment

SQL Single Line Comments Example

In this example, we use a single line comment to explain a query in SQL.

Query:

-- query to fetch customers records.
SELECT * FROM customers;

SQL Multi-Line Comments

SQL Multi-line comments contain multiple lines in a single comment. They start from one line and ends in a different line.

A multi-line comment starts with ‘/*’ and is terminated when ‘*/’ is encountered. 

Syntax

The syntax to insert a multi-line comment in SQL is:

/* multi line comment
another comment */

Multi-Line Comments Example

In this example, we will use the Multi-line comment to explain a complex query.

Query:

/*.
The query selects all the orders from the orders
table that were placed in the year 2022.
*/
SELECT * FROM orders WHERE YEAR(order_date) = 2022;

SQL In-Line Comments

SQL In-line comments are an extension of multi-line comments, these comments are used in between of a SQL statement.

An In-Line comment starts with ‘/*’ and end with ‘*/’.

Syntax

The syntax to use In-Line Comments in SQL is:

SELECT * FROM /* Customers; */ 

SQL In-Line Comments Example

In this example, we are using In-Line comments in SQL to explain information about table.

Query:

SELECT customer_name, 
/* This column contains the name of
the customer */ order_date / *
This column contains the date the
order was placed */ FROM orders;

Important Points About SQL Comments

  • SQL comments are annotations in the code that are not executed by the SQL engine, serving as notes or explanations for human readers to understand the code better.
  • There are 3 types of comments in SQL– Single Line comments, Multi-Line comments and In-line comments.
  • Proper use of comments in SQL can make scripts easier to understand, maintain, and debug, facilitating quicker reviews and onboarding of new team members
  • SQL comments are not supported in Microsoft Access databases.
  • Some database, like Oracle, provide additional features for commenting, such as the COMMENT ON statement to attach explanatory text to database objects.