Geek Slack

Getting Started with SQL Server
    About Lesson


    SQL INSERT INTO Statement


    SQL INSERT INTO Statement

    The INSERT INTO statement is used to insert new records into a table.

    Basic Syntax:

    INSERT INTO table_name (column1, column2, column3, ...)
    VALUES (value1, value2, value3, ...);

    Example 1: Inserting Data into All Columns

    INSERT INTO employees (employee_id, first_name, last_name, department, salary)
    VALUES (101, 'John', 'Doe', 'Sales', 60000);

    This query inserts a new employee into the “employees” table with the specified values for each column.

    Example 2: Inserting Data into Specific Columns

    INSERT INTO employees (employee_id, first_name, last_name)
    VALUES (102, 'Jane', 'Smith');

    This query inserts a new employee into the “employees” table, specifying values only for the “employee_id”, “first_name”, and “last_name” columns. The other columns will use their default values.

    Example 3: Inserting Multiple Rows

    INSERT INTO employees (employee_id, first_name, last_name, department, salary)
    VALUES
        (103, 'Alice', 'Brown', 'HR', 55000),
        (104, 'Bob', 'Johnson', 'IT', 70000),
        (105, 'Charlie', 'Davis', 'Marketing', 65000);

    This query inserts multiple new employees into the “employees” table with the specified values for each column.

    Example 4: Inserting Data with a Subquery

    INSERT INTO employees (employee_id, first_name, last_name, department, salary)
    SELECT employee_id, first_name, last_name, 'Sales', 50000
    FROM employees_archive
    WHERE start_date > '2023-01-01';

    This query inserts new employees into the “employees” table by selecting data from the “employees_archive” table for employees who started after January 1, 2023, and setting the “department” to ‘Sales’ and “salary” to 50000.

    The INSERT INTO statement is essential for adding new records to a table. It allows you to specify the values for each column directly or use a subquery to insert data from another table.