MySQL

Chapter 6 - DML (Data Manipulation Language)

UPSERT

The UPSERT operation in MySQL allows you to insert a new row or update an existing row if a conflict occurs (such as a duplicate key). This operation is especially useful when you want to ensure that data is inserted if it does not exist, or updated if it does. In MySQL, the UPSERT functionality can be achieved using INSERT ... ON DUPLICATE KEY UPDATE or the REPLACE statement. These commands are essential for managing dynamic data in applications like employee management systems, where new employees might be added, or existing records might need updates.

Example Scenario:

You have tables for company, employees, departments, and branches. For example, you may want to add a new employee, or update an existing employee’s details if they already exist in the database.


Steps to Use the UPSERT Operation:

  1. Basic Syntax of UPSERT using INSERT ... ON DUPLICATE KEY UPDATE
    • The general format for UPSERT withON DUPLICATE KEY is:
      INSERT INTO table_name (column1, column2, column3, ...)
      VALUES (value1, value2, value3, ...)
      ON DUPLICATE KEY UPDATE
      column1 = new_value1, column2 = new_value2, ...;
      
  2. Example 1: UPSERT for the employeesTable
    • Suppose the employeestable has the following structure:
      CREATE TABLE employees (
      employee_id INT AUTO_INCREMENT,
      first_name VARCHAR(50),
      last_name VARCHAR(50),
      department_id INT,
      salary DECIMAL(10, 2),
      hire_date DATE,
      PRIMARY KEY (employee_id)
      );
      
    • To insert a new employee or update an existing employee's salary if they already exist:
      INSERT INTO employees (employee_id, first_name, last_name, department_id, salary, hire_date)
      VALUES (1, 'John', 'Doe', 2, 60000, '2023-08-01')
      ON DUPLICATE KEY UPDATE
      salary = VALUES(salary);
      
    • Explanation:
      • If an employee with employee_id = 1 exists, the salary is updated to $60,000.
      • If no such employee exists, a new row is inserted.
  3. Example 2: UPSERT with Multiple Columns to Update
    • You can also update multiple columns if a duplicate key is found. For example, updating both salary and department_id:
      INSERT INTO employees (employee_id, first_name, last_name, department_id, salary, hire_date)
      VALUES (2, 'Jane', 'Smith', 3, 70000, '2023-07-15')
      ON DUPLICATE KEY UPDATE
      salary = VALUES(salary), department_id = VALUES(department_id);
      
    • Explanation:
      • If an employee with employee_id = 2 already exists, both their salary and department_idwill be updated.
  4. Using REPLACE as an Alternative for UPSERT
    • Another way to achieve the UPSERT behavior in MySQL is by using the REPLACE statement. This statement inserts a new row or replaces an existing one entirely if a primary key or unique key conflict occurs:
      REPLACE INTO employees (employee_id, first_name, last_name, department_id, salary, hire_date)
      VALUES (3, 'Alice', 'Williams', 4, 55000,'2023-06-10');
      
    • Explanation:
      • If an employee with employee_id = 3exists, the entire row is replaced with the new values.
      • If the employee does not exist, a new row is inserted.
  5. Example 3: UPSERT in the departments Table
    • Suppose you have a departments table with the following structure:
      CREATE TABLE departments (
      deapartment_id INT AUTO_INCREMENT,
      deapartment_name VARCHAR(50),
      branch_id INT,
      PRIMARY KEY (department_id)
      );
      
    • To insert a new department or update an existing department's branch:
      INSERT INTO departments (department_id, department_name, branch_id)
      VALUES (1,'HR',2)
      ON DUPLICATE KEY UPDATE
      branch_id = VALUES(branch_id);
      
    • Explanation:
      • If a department with department_id = 1exists, the branch_idis updated to 2.
      • If no such department exists, a new row is inserted.

    Notes on Using the UPSERT Operation:

    1. Handling Unique Keys and Primary Keys:
      • UPSERT works by checking for conflicts on unique keys or primary keys. If a conflict is found, the existing row is updated.
    2. REPLACE vs. INSERT ... ON DUPLICATE KEY UPDATE:
      • REPLACE deletes the existing row and inserts a new one, which may cause issues with foreign key constraints.
      • INSERT ... ON DUPLICATE KEY UPDATE is preferred when you only want to update specific columns without deleting and recreating the entire row.
    3. Updating Specific Columns:
      • When using ON DUPLICATE KEY UPDATE, you can choose which columns to update if a conflict occurs. Use the VALUES() function to reference the new values being inserted.
    4. Avoiding Full Row Replacement:
      • Unlike REPLACE, the ON DUPLICATE KEY UPDATE option only updates specific columns, which preserves the other existing data in the row.
    5. Real-World Usage in Company Databases:
      • For example, in a company database, the UPSERT operation can be used to add new employees or update their salaries without creating duplicate entries. Similarly, you can update department details if a department already exists or insert new data if it does not.

    By following these steps, beginners can effectively use the UPSERT operation in MySQL to insert or update data in tables related to a company's employees, departments, and branches. This allows for efficient data management without duplicate entries.

Tansy SQL Course | UPSERT | Chapter 6 | Lesson 4 - Video Thumbnail
Comments(0 comments)

Comments Not Found