SQL Comments



SQL Comments

SQL comments are used to add explanatory notes or remarks within SQL statements. This command is essential for improving code readability and maintainability by providing context and documentation.


Types of SQL Comments

  • -- Single-line comment: This type of comment starts with two hyphens (--) and continues to the end of the line.
  • /* Multi-line comment */: This type of comment starts with /* and ends with */, allowing for comments that span multiple lines.

Syntax

-- Single-line comment example
SELECT * FROM employees; -- This query selects all columns from the employees table

/* Multi-line comment example
   This query selects all columns from the employees table
   and retrieves all rows */
SELECT * FROM employees;

Example

Let's go through a complete example that includes creating a database, creating a table, inserting data into the table, and using comments to explain each step.

Step 1: Creating a Database

This step involves creating a new database named example_db. We use a single-line comment to explain this step.

-- Create a new database named example_db
CREATE DATABASE example_db;

Step 2: Creating a Table

In this step, we create a table named employees within the previously created database. We use a multi-line comment to explain the table structure.

USE example_db;

/* Create a table named employees
   with columns for employee_id, first_name, last_name, and email */
CREATE TABLE employees (
    employee_id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    email VARCHAR(100)
);

Step 3: Inserting Data into the Table

This step involves inserting some sample data into the employees table. We use single-line comments to explain each insertion.

-- Insert data into the employees table
INSERT INTO employees (first_name, last_name, email) VALUES ('John', 'Doe', 'john.doe@example.com'); -- Insert John Doe
INSERT INTO employees (first_name, last_name, email) VALUES ('Jane', 'Smith', 'jane.smith@example.com'); -- Insert Jane Smith
INSERT INTO employees (first_name, last_name, email) VALUES ('Alice', 'Johnson', 'alice.johnson@example.com'); -- Insert Alice Johnson
INSERT INTO employees (first_name, last_name, email) VALUES ('Bob', 'Brown', 'bob.brown@example.com'); -- Insert Bob Brown
INSERT INTO employees (first_name, last_name, email) VALUES ('Charlie', 'Davis', 'charlie.davis@example.com'); -- Insert Charlie Davis

Step 4: Retrieving Data from the Table

This step involves retrieving data from the employees table. We use a single-line comment to explain the query.

-- Select all data from the employees table
SELECT * FROM employees;

By using comments, we can make our SQL code more understandable and easier to maintain. Comments do not affect the execution of the SQL statements.