
For an instructor lead, in-depth look at learning SQL click below.
SQL, or Structured Query Language, is a powerful tool that helps us to interact with databases. As simple or as complex as your SQL statements might be, it’s essential that your code is well documented and commented. Whether your SQL code is used by a team or is part of a personal project, good practices on documentation and commenting are crucial for future troubleshooting, functionality updates, and understanding.
Why is Commenting Important?
Comments in SQL are the readable explanations in the code that allow you, and others, to understand what the code is doing. This is of utmost importance particularly when the code is being read by someone else. They provide a way of communicating what the code does without having to decipher the logic, or if the code fails to execute in a certain environment.
Types of Comments in SQL
SQL supports two types of comments: Single-line and multi-line comments.
Single-line Comments
As the name indicates, these types of comments take up only a single line in your code. Here’s the syntax to write a single-line comment:
|
1 2 3 4 |
-- This is a single line comment in SQL SELECT * FROM Employees |
In the above example, the comment starts with a double hyphen (–). The SQL server ignores everything that comes after the double hyphen on that line.
Multi-line Comments
Multi-line comments, as indicative from the name, span across multiple lines. Multi-line comments in SQL are enclosed within /* and */. Here’s how you can write multi-line comments:
|
1 2 3 4 5 |
/* This is a multi-line comment in SQL It spans multiple lines */ SELECT * FROM Employees |
Best Practices for Documentation and Commenting in SQL
1. Indicate the Purpose of the Code
All SQL scripts should start with a comment that explains the purpose of the script. This will give any reader a context of what to expect in the code.
2. Explain Complex Queries
For complex SQL queries, you should write comments that explain the logic behind the query. This helps any reader to understand your thought process while writing the query.
3. Comment on Major Changes
If you make a major change to a piece of SQL, always write a comment to indicate it. This is particularly useful in finding out where a potential bug might have been introduced into the code.
4. Be Brief and Specific
The comments should be as brief as possible while conveying the message. Avoid unnecessary statements to maintain clarity.
Proper documentation and commenting make your SQL code more understandable and maintainable. Even if it seems time-consuming, it’s a worthwhile investment that’ll pay off in the long-run.
