Skip to content

Lesson 8 – SQL Comments: Documenting Your Code

Two people sharing SQL Comments

Welcome back, master of syntax!

In our last lesson, we learned the essential grammar of SQL—the rules of the road for our City of Data. You now know how to write a valid, well-formatted SQL statement that the database engine can understand and execute.

But there’s another, equally important audience for your code: people. This includes your teammates, your manager, and most importantly, your future self who might look at your code six months from now with no memory of why you wrote it.

This is where the art of documentation comes in. A good data explorer doesn’t just find a path; they create a map for others to follow. They leave notes, warnings, and explanations. In the world of SQL, these crucial notes are called SQL comments.

This lesson will teach you everything you need to know about SQL comments. We’ll go beyond the basic syntax to understand why documenting your code is one of the most professional habits you can develop. You will learn not just how to write SQL comments, but why and when to write them effectively.

What Are SQL Comments? The Invisible Ink of Your Code

Let’s start with a simple definition.

SQL comments are lines of text within your SQL script that are completely ignored by the database engine. Their sole purpose is to provide context and explanations for human readers.

Think of it as writing in invisible ink. The SQL Engine, in its purely logical mission, doesn’t even see the comments. It reads right past them. But for any human looking at your script, these comments are the bright, colorful annotations that explain the journey.

Why is this so important?

  • Readability: Good comments explain the purpose of a complex query, making it easier for others to understand at a glance.
  • Collaboration: When working on a team, comments are essential for communicating your logic and intentions to your colleagues.
  • Debugging: They allow you to temporarily “turn off” parts of your code to test and find errors, a technique we will explore in detail.
  • Maintenance: When you need to update a query months later, well-placed SQL comments will be a lifesaver, dramatically reducing the time it takes to re-learn your own code.

Understanding how to use SQL comments effectively is a fundamental skill for writing clean, maintainable, and professional code.

person reading out sql comments on computer screen

Check Your Understanding

  1. Question: Does adding a hundred lines of comments to your SQL script make it run slower?
    • Answer: No, not at all. The SQL engine completely ignores all comments during the parsing stage, so they have zero impact on query performance.
  2. Question: What is the primary audience for SQL comments?
    • Answer: Human beings—your teammates, your manager, and your future self.

The Cartographer’s Tools: The Two Types of SQL Comments

The SQL standard provides two simple tools for leaving notes on your map. Mastering both is essential.

1. Single-Line Comments (--)

This is your go-to tool for short, quick annotations. A single-line comment starts with two hyphens (--) and tells the database engine to ignore everything that follows on that same line.

The Syntax:

-- This is a single-line comment.
SELECT first_name, last_name -- This is another comment, explaining the columns selected.
FROM Customers;
SQL

As you can see, you can place a single-line comment on its own line to describe the block of code that follows, or you can place it at the end of a line of code to provide a specific, targeted explanation.

Practical Example: Imagine you have a query to find high-value customers. You can use SQL comments to clarify the logic.

-- This query identifies high-value customers for a special marketing campaign.
-- A "high-value" customer is defined as anyone from Mumbai or Delhi.

SELECT
    email,
    first_name
FROM
    Customers
WHERE
    city = 'Mumbai' OR city = 'Delhi'; -- We are including both cities in this campaign.
SQL

This is much clearer than just seeing the code on its own.

Check Your Understanding

  1. Question: If you write SELECT -- first_name, last_name FROM Customers;, what will happen?
    • Answer: The database will ignore everything after the --, including the column names and the FROM clause, resulting in a syntax error because the SELECT statement is incomplete.
  2. Question: What is the main purpose of an inline comment (a comment at the end of a line of code)?
    • Answer: To provide a very specific clarification for that single line of code without interrupting the visual flow of the main query block.

2. Multi-Line (or Block) Comments (/* ... */)

Sometimes, a single line isn’t enough. You might need to write a detailed paragraph, include a list of changes, or temporarily disable a large chunk of code. For this, you use a multi-line or block comment.

A multi-line comment starts with a forward slash followed by an asterisk (/*) and ends with an asterisk followed by a forward slash (*/). Everything between these two markers is ignored, no matter how many lines it spans.

The Syntax:

/*
  This is a multi-line comment.
  It can span across several lines, making it perfect
  for detailed explanations or headers.
  Author: Your Name
  Date: July 13, 2025
*/
SELECT * FROM Products;
SQL

The Power of “Commenting Out” Code

One of the most powerful uses for block comments is debugging. Imagine you have a long, complex query that isn’t working correctly. You can “comment out” parts of it to test it piece by piece.

Example: Let’s say this query is giving an error. You suspect the problem is in the ORDER BY clause.

SELECT
    product_name,
    category,
    price
FROM
    Products
WHERE
    category = 'Electronics'
    AND price > 10000.00
ORDER BY
    product_name;
SQL

You can use a block comment to temporarily disable the ORDER BY clause and see if the rest of the query works.

SELECT
    product_name,
    category,
    price
FROM
    Products
WHERE
    category = 'Electronics'
    AND price > 10000.00;
/*
-- Temporarily disabling this to test the WHERE clause.
ORDER BY
    product_name;
*/
SQL

This technique is an indispensable troubleshooting skill, and it’s all made possible by effective use of SQL comments.

Check Your Understanding

  1. Question: Can you put a single-line comment inside a multi-line comment block?
    • Answer: Yes. Everything between the /* and */ markers is ignored, including other comment markers like --.
  2. Question: What is the primary advantage of a multi-line comment over multiple single-line comments?
    • Answer: It’s more convenient for long explanations and for “commenting out” large sections of code. You only need to type the start and end markers once.
  3. Question: Can you “nest” multi-line comments (put one /* ... */ block inside another)?
    • Answer: No. Most SQL dialects do not support nested block comments. The first */ encountered will close the comment block, which can lead to syntax errors.

Best Practices: The Art of Writing Good SQL Comments

Knowing the syntax is easy. Knowing what and when to comment is an art. A bad comment is often worse than no comment at all. Here are some professional best practices, inspired by coding principles from resources like Google’s SQL Style Guide.

1. Comment the “Why,” Not the “What”

Your code already says what it is doing. Your comments should explain why you are doing it.

Bad Comment (Useless):

-- Selects the first name and last name
SELECT first_name, last_name FROM Customers;
SQL

This comment is redundant. We can already see that the code selects the first and last name.

Good Comment (Useful):

-- We need the full name for the personalized email greeting.
SELECT first_name, last_name FROM Customers;
SQL

This comment provides valuable context. It explains the business reason behind the query.

2. Use Comments to Document Complex Logic

If a piece of your query involves a tricky business rule or a non-obvious calculation, that is the perfect place for a comment.

-- Calculate the final price, applying a 10% holiday discount
-- to all items in the 'Electronics' category.
SELECT
    product_name,
    price,
    price * 0.90 AS discounted_price -- 10% discount applied
FROM
    Products
WHERE
    category = 'Electronics';
SQL

3. Keep Comments Up-to-Date

An out-of-date comment that describes what the code used to do is incredibly misleading. If you change the logic of your query, make sure you update the comment that describes it.

4. Use Comments for TODOs

It’s common practice to leave notes for future work directly in the code. This helps you and your team keep track of needed improvements.

/*
  TODO: This query is a bit slow on a large dataset.
  We should investigate adding an index on the `category` column
  in a future release. - A. Explorer, 2025-07-13
*/
SELECT * FROM Products WHERE category = 'Books';
SQL

Conclusion: Your Legacy as a Data Explorer

You have now learned one of the most practical and professional skills in the SQL language. You know how to use both single-line and multi-line SQL comments not just as a feature, but as a powerful tool for communication and debugging.

Writing good code is about more than just getting the right answer from the database. It’s about creating solutions that are clear, maintainable, and easy for others to work with. Your SQL comments are your legacy. They are the helpful maps you leave behind, ensuring that the paths you discover today can be easily followed by others tomorrow.

Now that you know how to document your code, let’s look at the tools you’ll use to perform calculations and make comparisons.

➡️ Next Lesson: SQL Operators: A Comprehensive Guide

persone editing sql comments

Key Takeaways

  • SQL Comments are text in your script that the database ignores, intended for human readers.
  • There are two types: single-line comments (--) and multi-line comments (/* ... */).
  • The primary purpose of comments is to improve readability, aid in collaboration, and make maintenance easier.
  • A key professional practice is to comment the “why” (the business logic) not the “what” (the obvious syntax).
  • Multi-line comments are an essential tool for temporarily “commenting out” blocks of code for testing and debugging.

Frequently Asked Questions (FAQ)

1. Is it possible to over-comment my code?

Yes. Commenting on every single line or stating the obvious (like -- This is a SELECT statement) adds clutter and can make the code harder to read. Good commenting is about quality, not quantity. Comment on complex, non-obvious, or important parts of your code.

2. Are the comment styles (-- and /* */) the same in all SQL databases?

Yes, these two styles are part of the ANSI SQL standard and are supported by virtually all modern relational database systems, including PostgreSQL, MySQL, SQL Server, and Oracle.

3. My company has a rule against comments. Why would they do that?

While rare, some development philosophies argue that code should be “self-documenting.” This means that by using extremely clear table and column names and simple logic, the code itself should be so readable that it doesn’t require comments. While this is a noble goal, in the real world of complex business rules, good comments are almost always necessary.

4. Can I put a comment in the middle of a line of code?

No. A single-line comment (--) affects everything from the marker to the end of the line. You cannot resume the SQL code after it on the same line.

5. How do I quickly comment or uncomment a block of code in DBeaver (or another GUI)?

Most modern code editors and SQL clients have a keyboard shortcut for this. Typically, you can highlight a block of text and press Ctrl + / (on Windows/Linux) or Cmd + / (on macOS) to toggle comments on and off for that entire block. This is an extremely useful shortcut to learn.

6. Besides TODO, are there other common comment tags?

Yes, developers often use other tags to organize their notes. Some common ones include FIXME (to mark code that is broken and needs fixing), NOTE (to point out a specific detail), and OPTIMIZE (to mark code that works but could be made faster).

Join the conversation

Your email address will not be published. Required fields are marked *