What Is The Correct Way To Comment in SQL?
How do you properly add comments in SQL, and what are the correct ways to write them? Comments help explain queries, improve readability, and guide others in understanding the code, but using the right syntax is essential to avoid errors.
When writing SQL queries, adding comments is an important practice to make your code more readable, maintainable, and easier for others (or even your future self) to understand. But what is the correct way to comment in SQL, and how should you use them? SQL provides two primary methods: single-line and multi-line comments.
1. Single-Line Comments
- Use -- followed by your text.
- Everything after -- on that line is treated as a comment.
Example:
-- This query selects all data from employees
SELECT * FROM employees;
2. Multi-Line (Block) Comments
- Use /* to begin and */ to end the comment.
- Useful for larger explanations or temporarily disabling sections of code.
Example:
/* This query fetches
employee names and salaries */
SELECT name, salary FROM employees;
Key Points to Remember:
- Always use comments to clarify why you wrote the query, not just what it does.
- Avoid over-commenting simple queries, but explain complex logic.
- Keep comments up-to-date, otherwise they can cause confusion.
- SQL interprets comments as non-executable text, so they don’t affect performance.
In short, the correct way to comment in SQL depends on your needs—use -- for short explanations and /*...*/ for detailed notes. Writing clear and meaningful comments ensures that your SQL code remains professional, maintainable, and easy to follow.