SQL Comments
Comments let you annotate SQL scripts with explanatory notes and temporarily disable statements without deleting them.
What are SQL comments?
A comment is text inside a SQL script that the database engine ignores when it runs your code. Comments have no effect on the result of a query, so they are purely for the benefit of the people reading and maintaining the script. You use them to describe what a complex query does, to record why a particular decision was made, or to switch off a line of code so it does not execute.
Standard SQL supports two forms of comment: a single-line comment that runs to the end of the current line, and a multi-line comment that can span several lines. Both forms are widely supported across databases such as MySQL, PostgreSQL, SQL Server, Oracle, and SQLite.
Single-line comments
A single-line comment starts with two hyphens (--). Everything from the two hyphens to the end of that line is treated as a comment. You can place a single-line comment on its own line or add it to the end of a line that already contains SQL.
Using single-line comments
-- Select every employee in the sales department
SELECT first_name, last_name
FROM employees
WHERE department = 'Sales';
SELECT * FROM employees; -- this returns all columns and rowsYou can also use a single-line comment to disable one line of code. When you place -- at the start of a statement, the database skips that line entirely, which is a quick way to test a script without a particular clause.
Disabling code with a comment
SELECT first_name, last_name
FROM employees
-- WHERE department = 'Sales'
ORDER BY last_name;Multi-line comments
A multi-line comment begins with /* and ends with */. Everything between those markers is ignored, even if it stretches over many lines. This form is useful for longer explanations, for a header block at the top of a script, or for commenting out a whole section of a query at once.
Using a multi-line comment
/*
Monthly revenue report
Author: Data team
Groups orders by product and sums the amount
*/
SELECT product_id, SUM(amount) AS total_revenue
FROM orders
GROUP BY product_id;Tips for writing good comments
- Explain why a query is written a certain way, not just what each line does, since the code already shows the what.
- Keep comments up to date; a comment that no longer matches the code is more confusing than no comment at all.
- Use a comment block at the top of a saved script to record its purpose, author, and any assumptions.
- Comment out clauses while debugging to isolate which part of a query causes an unexpected result.
Exercise: SQL Comments
Which syntax creates a single-line comment in standard SQL?