Sql Update Multiple Rows With Different Values

5 min read

Updating records is one of the most fundamental operations in database management, yet the complexity rises significantly when you need to modify multiple rows with distinct values in a single operation. And while a standard UPDATE statement with a WHERE clause applies the same change to every matching row, real-world scenarios often demand granular control—adjusting a specific column for ID 1 to 'Active', ID 2 to 'Pending', and ID 3 to 'Archived' simultaneously. Mastering sql update multiple rows with different values is essential for maintaining data integrity, optimizing application performance, and reducing the overhead of round-trips between your application server and the database Nothing fancy..

Understanding the Core Challenge

By default, SQL is set-based. A standard statement looks like this:

UPDATE users SET status = 'Active' WHERE id IN (1, 2, 3);

This applies 'Active' to all three rows. But what if row 1 needs 'Active', row 2 needs 'Inactive', and row 3 needs 'Suspended'? In real terms, running three separate UPDATE statements works, but it incurs network latency, transaction log overhead, and potential locking contention for each execution. For high-throughput systems, batching these changes into a single atomic statement is vastly superior Simple, but easy to overlook..

Some disagree here. Fair enough.

There are three primary patterns to achieve this: the CASE expression, the VALUES clause (often combined with a JOIN), and database-specific upsert syntax like ON CONFLICT or ON DUPLICATE KEY UPDATE. The right choice depends on your specific RDBMS (PostgreSQL, MySQL, SQL Server, Oracle) and the volume of data Which is the point..

Method 1: The CASE Expression (Universal Standard)

The most portable, ANSI-SQL compliant way to handle conditional updates is the CASE expression inside the SET clause. This works identically across PostgreSQL, MySQL, SQL Server, Oracle, and SQLite Small thing, real impact..

Syntax Pattern

UPDATE target_table
SET target_column = CASE
    WHEN condition_1 THEN value_1
    WHEN condition_2 THEN value_2
    WHEN condition_3 THEN value_3
    ELSE target_column -- Crucial: keeps original value if no match
END
WHERE id IN (id_1, id_2, id_3);

Practical Example

Imagine an employees table where you need to adjust salaries based on performance reviews Which is the point..

UPDATE employees
SET salary = CASE
    WHEN employee_id = 101 THEN 75000
    WHEN employee_id = 102 THEN 82000
    WHEN employee_id = 103 THEN 68000
    ELSE salary
END
WHERE employee_id IN (101, 102, 103);

Why the ELSE clause matters: Without ELSE salary (or ELSE target_column), any row matching the WHERE clause but not listed in the WHEN conditions would be set to NULL. The WHERE clause here acts as a safety net, limiting the scan to only the rows you intend to touch, which improves performance by avoiding a full table scan Took long enough..

Pros and Cons

  • Pros: Universal compatibility; single statement; easy to read for small batches.
  • Cons: Verbose for large datasets (hundreds of rows); the query string length can hit database limits; maintenance becomes tedious if generated dynamically.

Method 2: Updating via a Derived Table / JOIN (Set-Based Approach)

For larger batches—typically anything over 20–50 rows—the CASE statement becomes unwieldy. A cleaner, set-based approach involves joining the target table against a virtual table (derived table) containing the new values. This treats the update as a relational operation rather than a procedural list of conditions Small thing, real impact..

PostgreSQL / SQL Server / Oracle Syntax (Standard JOIN)

Most modern databases support updating via a JOIN or a FROM clause.

PostgreSQL:

UPDATE employees e
SET salary = vals.new_salary,
    department = vals.new_dept
FROM (VALUES
    (101, 75000, 'Engineering'),
    (102, 82000, 'Marketing'),
    (103, 68000, 'Sales')
) AS vals(emp_id, new_salary, new_dept)
WHERE e.employee_id = vals.emp_id;

SQL Server:

UPDATE e
SET e.salary = vals.new_salary,
    e.department = vals.new_dept
FROM employees e
INNER JOIN (VALUES
    (101, 75000, 'Engineering'),
    (102, 82000, 'Marketing'),
    (103, 68000, 'Sales')
) AS vals(emp_id, new_salary, new_dept) ON e.employee_id = vals.emp_id;

Oracle (MERGE Statement): Oracle prefers the MERGE statement for this pattern, which is incredibly powerful for "Upsert" logic (Update or Insert).

MERGE INTO employees e
USING (
    SELECT 101 AS emp_id, 75000 AS new_salary, 'Engineering' AS new_dept FROM dual UNION ALL
    SELECT 102, 82000, 'Marketing' FROM dual UNION ALL
    SELECT 103, 68000, 'Sales' FROM dual
) vals
ON (e.employee_id = vals.emp_id)
WHEN MATCHED THEN
    UPDATE SET e.salary = vals.new_salary, e.department = vals.new_dept;

MySQL Specifics (VALUES / CTE)

Modern MySQL (8.0+) supports Common Table Expressions (CTEs) and the VALUES row constructor, making this pattern clean:

WITH new_data (emp_id, new_salary, new_dept) AS (
    SELECT 101, 75000, 'Engineering' UNION ALL
    SELECT 102, 82000, 'Marketing' UNION ALL
    SELECT 103, 68000, 'Sales'
)
UPDATE employees e
JOIN new_data nd ON e.employee_id = nd.emp_id
SET e.salary = nd.new_salary, e.department = nd.new_dept;

Advantages of the Derived Table Method

  1. Readability: Data and logic are separated. The "payload" looks like a dataset.
  2. Maintainability: Generating a VALUES list programmatically (e.g., from a CSV, JSON array, or application loop) is significantly easier than building a massive CASE string.
  3. Multi-Column Updates: Updating 5 columns for 100 rows requires only one SET clause mapping columns, whereas CASE requires 5 separate CASE blocks.
  4. Performance: The optimizer treats this as a join, often utilizing Hash Match or Nested Loops joins which are highly efficient for bulk modifications.

Method 3: Bulk Upserts (ON CONFLICT / ON DUPLICATE KEY)

Often, the requirement to "update multiple rows with different values" arises during an ETL process or API sync where the data might exist. And you want to insert new rows and update existing ones in a single pass. This is the Upsert pattern.

PostgreSQL (ON CONFLICT)

INSERT INTO employees (employee_id, salary, department)
VALUES

(101, 75000, 'Engineering'),
    (102, 82000, 'Marketing'),
    (103, 68000, 'Sales')
ON CONFLICT (employee_id) DO UPDATE SET
    salary = EXCLUDED.salary,
    department = EXCLUDED.department;

The EXCLUDED pseudo-table holds the values proposed for insertion. When a conflict occurs on the employee_id unique constraint, PostgreSQL updates the existing row using those incoming values instead of throwing an error Took long enough..

MySQL (ON DUPLICATE KEY UPDATE)

MySQL handles the same pattern with ON DUPLICATE KEY UPDATE:

INSERT INTO employees (employee_id, salary, department)
VALUES
    (101, 75000, 'Engineering'),
    (102, 82000, 'Marketing'),
    (103, 68000, 'Sales')
ON DUPLICATE KEY UPDATE
    salary = VALUES(salary),
    department = VALUES(department);

(In MySQL 8.0.19 and later, you can also use row-value aliases instead of the VALUES() function, but the behavior is identical.)

SQL Server (MERGE for Upsert)

While Oracle’s MERGE was shown earlier for updates, SQL Server uses the same statement to achieve a true upsert—inserting when no match exists and updating when one does:

MERGE INTO employees AS target
USING (VALUES
    (101, 75000, 'Engineering'),
    (102, 82000, 'Marketing'),
    (103, 68
Fresh Out

Newly Published

Handpicked

While You're Here

Thank you for reading about Sql Update Multiple Rows With Different Values. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home