SQL Comments Tutorial
Example Table
We will use the following table named employees
for our examples:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10, 2)
);
INSERT INTO employees (employee_id, employee_name, department, salary) VALUES
(1, 'John Doe', 'HR', 50000.00),
(2, 'Jane Smith', 'Finance', 60000.00),
(3, 'Sam Brown', 'IT', 70000.00),
(4, 'Nancy White', 'HR', 55000.00),
(5, 'Mike Green', 'Finance', 65000.00);
employee_id | employee_name | department | salary |
---|---|---|---|
1 | John Doe | HR | 50000.00 |
2 | Jane Smith | Finance | 60000.00 |
3 | Sam Brown | IT | 70000.00 |
4 | Nancy White | HR | 55000.00 |
5 | Mike Green | Finance | 65000.00 |
Using SQL Comments
SQL comments are used to explain sections of SQL statements or to prevent execution of SQL statements. Comments are ignored by the SQL engine.
Single-line Comments
Single-line comments start with two consecutive hyphens (--
). Any text following --
to the end of the line is considered a comment.
-- This is a single-line comment
SELECT employee_name, salary
FROM employees
WHERE department = 'HR';
Result:
employee_name | John Doe |
---|---|
salary | 50000.00 |
employee_name | Nancy White |
salary | 55000.00 |
Multi-line Comments
Multi-line comments start with /*
and end with */
. Any text between /*
and */
is considered a comment.
/* This is a multi-line comment
It can span multiple lines */
SELECT employee_name, salary
FROM employees
WHERE department = 'Finance';
Result:
employee_name | Jane Smith |
---|---|
salary | 60000.00 |
employee_name | Mike Green |
salary | 65000.00 |
Using Comments to Prevent Execution
Comments can also be used to prevent execution of SQL statements. This is useful for debugging purposes.
-- SELECT * FROM employees; -- This statement will not be executed
Result:
employee_id | |
---|---|
employee_name | |
department | |
salary |