Advertisement
❮ Previous: SQL Order By Next: SQL Select Top / Limit / Rownum ❯

SQL Comments

SQL comments are non-executable lines of text that you add to your code to explain its purpose. The database engine completely ignores these comments during execution.

Writing clear comments makes your scripts easier for others (and your future self) to understand, debug, and maintain.


Single-Line Comments (--)

To create a single-line comment, type two consecutive hyphens (--). Anything you type after these hyphens on that same line will be completely ignored by the database.

-- Fetch all active employees from the database
SELECT first_name, last_name FROM employees
WHERE status = 'Active'; -- Filters out terminated staff

Note: Make sure to include a space after the two hyphens to ensure all database engines interpret it properly.


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

To write longer comments that span multiple lines, or to temporarily disable a large block of code while testing, wrap your text in /* and */.

/*
This query generates the end-of-year sales report.
It calculates the total revenue per department
and filters out any internal test transactions.
*/
SELECT department, SUM(sale_amount)
FROM sales
WHERE is_test_account = 0
GROUP BY department;

Commenting Out Code for Debugging

Comments are incredibly helpful when you are trying to find an error in your code. You can use them to isolate specific lines and see exactly what is broken.

SELECT first_name, last_name, salary
FROM employees
WHERE department = 'IT'
-- AND salary > 80000  <- Commenting this out lets you check if the query works without this filter
ORDER BY salary DESC;

Advertisement

Best Practices

❮ Previous: SQL Order By Next: SQL Select Top / Limit / Rownum ❯
Advertisement