SQL comments are used to add notes or explanations to the code, making it more readable and understandable for others.
Comments in SQL can be added to the entire query or to specific lines of the query.
In SQL, comments are denoted by a double dash — at the beginning of the line.
-- This is a comment SELECT * FROM employees;
Multi-line comments can be added using the slash-asterisk /* at the beginning and the asterisk-slash */ at the end of the comment.
/* This is a multi-line comment */ SELECT * FROM employees;
Using Comments in SQL Queries
Comments can be added to any part of an SQL query, including the SELECT, FROM, WHERE, and ORDER BY clauses.
For example, the following query uses a comment to explain the purpose of the query:
-- This query retrieves the names and departments of all employees SELECT name, department FROM employees;
Another example, this query uses a comment to explain the purpose of the WHERE clause:
-- Retrieve all the records where salary is greater than 50000 SELECT * FROM employees WHERE salary > 50000;
It is also possible to add comments to specific lines within a query.
SELECT name, -- retrieve name department -- retrieve department FROM employees;
Comments are an important part of writing readable and maintainable SQL code.
They can be used to explain the purpose of a query or to add notes about specific parts of the query.
It is a good practice to include comments in your SQL code, especially when working on a team or sharing the code with others.