SQL INSERT

SQL INSERT

 Understanding SQL INSERT

The SQL INSERT statement is used to add new rows of data into a table. It is one of the fundamental Data Manipulation Language (DML) operations in SQL.


Syntax of SQL INSERT

1. Inserting Data into All Columns

INSERT INTO table_name VALUES (value1, value2, ..., valueN);
  • table_name: The name of the table where data will be inserted.
  • VALUES: Specifies the data to be inserted.
  • value1, value2, ..., valueN: The values for each column in the table.

2. Inserting Data into Specific Columns

INSERT INTO table_name (column1, column2, ..., columnN) VALUES (value1, value2, ..., valueN);
  • Allows you to insert values into specific columns, leaving others as default or NULL.

3. Inserting Multiple Rows

INSERT INTO table_name (column1, column2, ..., columnN) VALUES (value1_1, value1_2, ..., value1_N), (value2_1, value2_2, ..., value2_N);

4. Inserting Data from Another Table

INSERT INTO table_name (column1, column2, ..., columnN) SELECT column1, column2, ..., columnN FROM another_table WHERE condition;

Examples of SQL INSERT

1. Insert a Single Row into All Columns

Insert a new employee record into the employees table.

INSERT INTO employees VALUES (101, 'John Doe', 'IT', 60000, '2025-01-01');

Explanation:
This query inserts a single row with values corresponding to all columns in the employees table.

2. Insert into Specific Columns

Insert a new employee with only ID, name, and department specified.

INSERT INTO employees (employee_id, name, department) VALUES (102, 'Jane Smith', 'HR');

Explanation:
This query inserts values into the specified columns, while other columns take their default values (or NULL if no default is set).

3. Insert Multiple Rows

Add multiple employees in one query.

INSERT INTO employees (employee_id, name, department, salary, hire_date) VALUES (103, 'Mike Brown', 'Finance', 75000, '2025-02-01'), (104, 'Emily White', 'Marketing', 72000, '2025-03-01');

Explanation:
This query inserts two rows of employee data in a single operation.

4. Insert Data from Another Table

Copy all employees from the temp_employees table to the employees table.

INSERT INTO employees (employee_id, name, department, salary, hire_date) SELECT employee_id, name, department, salary, hire_date FROM temp_employees WHERE department = 'IT';

Explanation:
This query fetches data from the temp_employees table where the department is 'IT' and inserts it into the employees table.

5. Insert Using Default Values

Add a new product with default price and stock.

INSERT INTO products (product_id, product_name) VALUES (201, 'Laptop');

Explanation:
This query inserts a new product, while the default values for price and stock (if defined) are automatically applied.

Using SQL INSERT with RETURNING

In databases like PostgreSQL, you can use the RETURNING clause to retrieve the inserted data.

INSERT INTO employees (name, department, salary) VALUES ('Sara Connor', 'Sales', 68000) RETURNING employee_id, hire_date;

Explanation:
This query inserts a new employee and returns the employee_id and hire_date of the inserted record.

Best Practices for SQL INSERT

  1. Specify Columns Explicitly:
    Always specify column names to make the query more readable and prevent errors if the table structure changes.

  2. Use Transactions for Bulk Inserts:
    For inserting large datasets, use transactions to maintain data integrity.

  3. Avoid Duplicate Inserts:
    Use constraints like PRIMARY KEY or UNIQUE to prevent duplicate entries.

  4. Validate Data Types:
    Ensure the data being inserted matches the column data types to avoid runtime errors.

  5. Index Columns for Performance:
    Index the table appropriately to optimize inserts, especially for large datasets.

Common Errors and How to Fix Them

  1. Column Count Mismatch:
    Error: "Number of values doesn’t match the number of columns."
    Fix: Ensure the number of values matches the specified columns or all table columns.

  2. Data Type Mismatch:
    Error: "Cannot insert value into a column due to data type incompatibility."
    Fix: Check and match the data types of values and columns.

  3. Primary Key Violation:
    Error: "Duplicate entry for a primary key."
    Fix: Ensure that the primary key values are unique or used INSERT IGNORE (if supported).

  4. NULL Constraint Violation:
    Error: "Cannot insert NULL into a NOT NULL column."
    Fix: Provide valid values for columns with the NOT NULL constraint.

Alternatives to INSERT

  1. INSERT IGNORE:
    Skips inserting rows that cause errors, like primary key violations (e.g., in MySQL).

  2. REPLACE:
    Replaces existing rows with new data if a primary key or unique constraint is violated.

  3. UPSERT (INSERT ON CONFLICT):
    Databases like PostgreSQL, are used INSERT ON CONFLICT to handle duplicates gracefully.

    INSERT INTO employees (employee_id, name, salary) VALUES (101, 'John Doe', 60000) ON CONFLICT (employee_id) DO UPDATE SET salary = EXCLUDED.salary;

Real-World Use Cases of SQL INSERT

  1. Adding New Records:
    Insert new customers, orders, or transactions into a database.

  2. Bulk Data Loading:
    Insert large datasets into a table for analysis or processing.

  3. Data Migration:
    Transfer data between tables or databases.

  4. Audit Trails:
    Record logs or history by inserting events into an audit table.

Conclusion

The SQL INSERT statement is essential for adding data to your database. It provides flexibility through various options like inserting specific columns, multiple rows, or data from subqueries. By understanding its syntax and best practices, you can efficiently manage data insertion in your SQL operations.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close