Skip to main content
HomeTutorialsSQL

How to Create Comments in SQL

Review three methods to add comments in SQL: single-line comments, multiline comments, and inline comments using the following syntax: --, /*, and */.
May 31, 2024  · 5 min read

SQL, which stands for Structured Query Language, is a powerful language for managing and manipulating relational databases. While SQL queries may seem self-explanatory at first glance, adding comments in SQL statements can improve the readability and maintainability of your code.

In this tutorial, we’ll see how to add comments in SQL to make your code simpler and easier to read.

The Quick Answer: How to Create Comments in SQL

There are three ways to add comments to your SQL queries:

  1. Single-Line Comments: Single-line comments start with -- double hyphens.

  2. Inline Comments: Inline comments start with -- after the SQL statement on the same line.
  3. Multiline Comments or Block Comments: Multiline comments start  with /* and end with */.

 -- Single line comment
SELECT * 
FROM TABLE

SELECT * 
FROM TABLE -- Inline comment

/* Multiline
comment */ 
SELECT * 
FROM TABLE  

Why are SQL Comments Important?

Here are three key reasons why SQL comments are important:

  • Clarifying the Code's Purpose: Comments explain the code's purpose and logic, making it easier for others and yourself to understand when you review your code later.
  • Enhancing Teamwork: Comments facilitate teamwork by documenting the code for other developers, helping them to comprehend your work.
  • Aiding in Debugging and Optimization: Comments simplify the process of debugging and optimizing the code over time, making it more manageable to identify and correct issues.

Types of SQL Comments

Depending on your needs and preferences, there are three ways to add comments in SQL scripts.

Single-line comments

If your comment fits well within a single line, use double hyphens. Typically, you would place such comments above the relevant block of code to provide context.

--select the department name from the department table
SELECT dept_name
FROM employees.departments;

Inline comments

As we can see in the following example, single-line and inline comments in SQL use the same syntax and are essentially the same; the distinction lies in where and how they are placed. Inline comments tend to be used to explain a specific part of the query.

SELECT DISTINCT title -- It excludes duplicate titles using the DISTINCT keyword.
FROM employees.titles
ORDER BY title ASC -- The results are sorted alphabetically by the 'title' column.
LIMIT 10;

Multiline comments or block comments

You can use multiline comments in SQL to add longer comments across multiple lines. To add multiline comments, enclose your text between /* and */. The SQL interpreter will ignore any text enclosed between /* and */.

/*
This query retrieves the employee number, first name, last name, and gender
from the 'employees' table in the 'employees' database.
It filters the results only to include male employees, limiting to 4 rows.
*/
SELECT emp_no, first_name, last_name, gender
FROM employees.employees
WHERE employees.employees.gender = 'M'
LIMIT 4;

Best Practices for Writing SQL Comments

To ensure your comments are both concise and informative throughout your codebase, it is important to adhere to best practices. Let's review some of the guidelines below. 

Clarity and readability

Avoid using overly complex or technical terms in your comments. This will ensure that they are clear and concise so that anyone can understand, even those unfamiliar with the codebase.

Add relevant information

Make sure that the information you provide is accurate and directly relevant to the code it describes. It should explain the reasoning behind complex logic. Avoid including sensitive information in comments, such as passwords and API keys.

Update regularly

Outdated comments can mislead and contribute to technical debt. That’s why you should review and update your comments as you update the code to reflect the latest changes.

Avoid redundancy

Comments should not simply restate what the code is doing. Instead, comments should explain the "why" behind the code – the purpose or the context that’s not immediately apparent from the code itself.

Common Mistakes in SQL Commenting

Commenting your SQL code is super important for keeping things organized and understandable, especially if you have to revisit your code months later. But even with the best intentions, it's easy to fall into traps that make your comments more confusing than helpful. Here are some common mistakes to avoid when writing SQL comments:

Ambiguous or misleading comments

Write concise and unambiguous comments that provide value to the reader. Unclear or inaccurate comments are worse than no comments.

Over-commenting code

While comments are helpful, over-commenting can make the code harder to read and maintain. Try to focus on explaining the high-level purpose and any non-obvious aspects of the code.

Let’s take a look at a bad example:

Bad commenting example in SQL

Comment in an SQL query. Image by Author.

As we can see, because our variables had explicit names, the comments just restated the code without providing additional context or explaining its purpose.

Inconsistent commenting style

Inconsistent styles are distracting and make the code harder to read. To avoid this, use a consistent commenting style throughout your codebase. 

  • Capitalization: Maintaining consistent capitalization makes your code easier to read and understand.
  • Punctuation: Ending all comments with periods can be a good practice, but it is not a strict rule. The main goal is consistency.
  • Formatting: By defining clear guidelines for using block comments versus inline comments, you ensure consistency.

Lack of context

The following example includes a high-level description of our SQL code's purpose: "Retrieve customer orders for reporting." While accurate, it lacks the context needed to help the reader fully understand the code.

/*
* Retrieve employees' data for reporting
*/
SELECT e.first_name, e.last_name, s.salary
FROM employees.employees e
JOIN employees.salaries s ON e.emp_no = s.emp_no
WHERE s.salary > 150000
ORDER BY s.salary DESC;

To improve our comment, we can update to include more detail.

/* Retrieve employees' names and salaries where salary is above $150,000
as part of the monthly HR reporting process.
*/
SELECT e.first_name, e.last_name, s.salary
FROM employees.employees e
JOIN employees.salaries s ON e.emp_no = s.emp_no
WHERE s.salary > 150000
ORDER BY s.salary DESC;

Advanced Uses of SQL Comments

In addition to enhancing readability, SQL comments also aid in the coding process. In this section, we explore advanced uses of SQL comments, including embedding metadata, debugging SQL code, and temporarily disabling code. These techniques help streamline coding, making it easier to manage and troubleshoot your SQL scripts effectively.

Embedding metadata

You can use comments to embed metadata about the SQL code, such as the author name and date of creation or modification.

/*
Author: DataCamp
Date: 2024-05-28
Purpose: Retrieve employees' credentials for their record
*/
SELECT emp_no, first_name, last_name
FROM employees.employees

Debugging SQL code

You can comment out sections of your SQL code to isolate and test specific parts. This can help you pinpoint where an issue might be occurring.

/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;*/
SELECT * FROM Categories;

Temporarily disabling code

You can temporarily disable SQL code using single-line comments (--) or multiline comments in SQL (/* ... */). This way, you can keep the code in the query without executing it, which can be useful for testing only specific portions of your SQL code.

SELECT column1, column2
FROM table1
WHERE condition1
/*
AND condition2
OR condition3
*/

Myths and Misconceptions

Despite its widespread use, there are a few persistent myths and misconceptions about SQL comments.

Myth No. Myth Reality
1 SQL comments slow down execution. The SQL engine ignores comments, so they have no impact on performance.
2 SQL comments make the code harder to read and understand. Well-written comments have the opposite effect: They can make the code easier to read.
3 SQL comments are only useful for beginners. Even experienced developers can benefit from well-written comments, especially when working on complex queries or revisiting code after a long time.

Final Thoughts

While it may seem insignificant to SQL development, comments can improve the code and make it easier to understand. By writing clear and well-structured comments, developers can ensure their SQL code remains accessible even years after its initial creation.

If you are just starting your SQL journey, understanding the basics through a course like SQL Fundamentals can help you grasp the importance of commenting early on. As you progress, earning a SQL Associate Certification validates your skills and shows that you can write clear, well-documented code. To further enhance your skills, Intermediate SQL dives deeper into more complex queries where detailed comments can be used for things like debugging.


Photo of Laiba Siddiqui
Author
Laiba Siddiqui
LinkedIn
Twitter

I'm a content strategist who loves simplifying complex topics. I’ve helped companies like Splunk, Hackernoon, and Tiiny Host create engaging and informative content for their audiences.

Frequently Asked Questions

How can I ensure my SQL comments are understandable by new team members?

Use clear and descriptive comments that explain the purpose and functionality of the code effectively.

How do SQL comments help in debugging?

SQL comments can help debug by providing additional code context. This helps in identifying and fixing errors more efficiently.

Are SQL comments necessary for all SQL queries?

No, SQL comments are not necessary for all SQL queries. However, they are highly recommended for complex queries and for queries that are difficult to understand without additional context.

Are there any specific tools or interfaces that have additional restrictions on comments?

Some tools, such as SQLPlus, may have additional restrictions on comments. For example, SQLPlus does not allow a blank line inside a multiline comment.

Is it true that only beginners need to write comments in SQL?

No, even experienced developers benefit from well-written comments, especially when working on complex queries or revisiting code after a long time.

Topics

Learn SQL with DataCamp

Course

Introduction to SQL

2 hr
739.2K
Learn how to create and query relational databases using SQL in just two hours.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

tutorial

SELECTing Multiple Columns in SQL

Learn how to easily select multiple columns from a database table in SQL, or select all columns from a table in one simple query.
DataCamp Team's photo

DataCamp Team

3 min

tutorial

Insert Into SQL Tutorial

SQL's "INSERT INTO" statement can be used to add rows of data to a table in the database.
DataCamp Team's photo

DataCamp Team

3 min

tutorial

SQL DML Commands: Mastering Data Manipulation in SQL

Learn more about Data Manipulation Language (DML), how it compares to DQL and DDL, and master DML commands including SELECT, INSERT, DELETE, and UPDATE.
Dustin Luchmee's photo

Dustin Luchmee

6 min

tutorial

SQL: Reporting and Analysis

Master SQL for Data Reporting & daily data analysis by learning how to select, filter & sort data, customize output, & how you can report aggregated data from a database!
Hafsa Jabeen's photo

Hafsa Jabeen

37 min

code-along

Getting Started in SQL

Learn how to write basic queries in SQL and find answers to business questions.
Kelsey McNeillie's photo

Kelsey McNeillie

code-along

SQL for Absolute Beginners

Start from the very basics of what SQL is and why it's essential, move through key components such as retrieving data from databases, manipulation of data, and basic SQL queries.
Adel Nehme's photo

Adel Nehme

See MoreSee More