🇯🇵 日本語 | 🇺🇸 English | 🇪🇸 Español | 🇵🇹 Português | 🇹🇭 ไทย | 🇨🇳 中文

【SQL UPDATE Tutorial】How to Safely Update Existing Data with SET and WHERE

A user changes their email address, a product's price is revised, a blog post's status changes from "draft" to "published"—when operating a web application, situations where you need to change previously registered data occur daily. The crucial role of "rewriting existing data" is handled by SQL's UPDATE statement.

The UPDATE statement is a command for updating a database record with new information. However, while this command is very powerful, it also carries the risk that a single mistake can lead to an irreversible disaster. The factor that determines this fate is the presence of the WHERE clause.

This article will explain everything from the basic usage of the UPDATE statement to advanced techniques like updating multiple columns simultaneously. Above all, our primary goal is to engrave the ironclad rule—"NEVER forget the WHERE clause"—into your mind. Let's acquire the skill to update data safely and reliably while trying out copy-and-paste code.


Preparation: Let's Get Our User Data Ready

To try out the operations, we first need some source data. This time, we'll create a simple users table to manage user information and register a few users. All examples in this article will target this table.

-- Drop the users table if it exists (for repeatable testing)
DROP TABLE IF EXISTS users;

-- Create a new users table
CREATE TABLE users (
  id INTEGER PRIMARY KEY,
  username TEXT NOT NULL,
  email TEXT NOT NULL,
  points INTEGER DEFAULT 0,
  last_login_date DATE
);

-- Insert initial data
INSERT INTO users (id, username, email, points, last_login_date) VALUES
(1, 'Yamada Taro', 'yamada@example.com', 50, '2025-06-15'),
(2, 'Suzuki Hanako', 'suzuki@example.com', 120, '2025-06-20'),
(3, 'Tanaka Jiro', 'tanaka@example.com', 300, '2025-06-28'),
(4, 'Sato Misaki', 'sato@example.com', 550, '2025-06-30'),
(5, 'Ito Kenta', 'ito@example.com', 80, '2025-05-30');

With that, our data for five users is ready to be used for update operations.


Crucial: The Horror of Forgetting the `WHERE` Clause (The Danger of Updating All Records)

Before we get to the main content, let's start with the absolute worst mistake you can make with an UPDATE statement. That is, forgetting to include the WHERE clause.

The basic structure of an UPDATE statement is UPDATE table_name SET column_name = new_value WHERE condition;. This WHERE clause is a safety device for narrowing down the update target, specifying which records to update. If you forget this safety device, what do you think will happen?

For example, imagine you're running a campaign to set all users' points to 50, and in a hurry, you execute the following query.

-- 【NEVER RUN THIS CARELESSLY!】An UPDATE statement without a WHERE clause
UPDATE users SET points = 50;

This query has no WHERE clause. The database interprets this as "for all records in the users table, set the points column to 50." As a result, Sato-san's hard-earned 550 points, along with every other user's data, will be mercilessly overwritten to 50 points.

It's like needing to talk to a specific person but shouting "Hey, you!" to everyone in the room. When using an UPDATE statement, always double-check and explicitly specify the update target with a WHERE clause. This is the absolute rule when learning the UPDATE statement.


【The Basics】Updating a Single, Specific Record

Now, let's pull ourselves together and look at the correct way to use it. The most basic case is updating a single, specific record using a primary key (like id). This is safe because it guarantees the target is precisely one record.

Scenario: "User Tanaka with ID 3 has changed his email address."

UPDATE users
SET email = 'jiro.tanaka@new-example.com'
WHERE id = 3;

By specifying WHERE id = 3, we have accurately narrowed down the target to the record with ID 3. The SET clause rewrites the value of the -email column to the new address.

Let's check if it was updated. We'll display only the user with ID 3 using a SELECT statement.

SELECT * FROM users WHERE id = 3;

Result:

id | username    | email                       | points | last_login_date
---|-------------|-----------------------------|--------|----------------
3  | Tanaka Jiro | jiro.tanaka@new-example.com | 300    | 2025-06-28

You can see that the email has been correctly updated. This is the basic and safest way to use the UPDATE statement.


【Application 1】Updating Multiple Columns Simultaneously

It's also common to want to update the values of multiple columns at once. For example, when a user logs in, you might want to update both their last login date and their point balance.

You can update multiple columns at once by listing multiple "column_name = value" pairs in the SET clause, separated by commas (,).

Scenario: "User Suzuki with ID 2 has logged in, so update her last login date and add 10 points as a login bonus."

UPDATE users
SET 
  last_login_date = '2025-07-01',
  points = 130
WHERE
  id = 2;

Just like that, you can efficiently update data by listing multiple changes in the SET clause.


【Application 2】Updating Multiple Records That Match a Condition

The condition in the WHERE clause isn't limited to the primary key; you can use the values of other columns as well. This allows you to update multiple records that meet a specific condition all at once.

Scenario: "Give a 100-point bonus to all users who currently have 300 or more points."

In this case, the target for the update is "users with points greater than or equal to 300." Also, the new point value will be "the current points + 100." The UPDATE statement allows you to use the column's own current value in the calculation for the update.

UPDATE users
SET points = points + 100
WHERE points >= 300;

Executing this query will update the points for Tanaka (ID 3, 300 points) and Sato (ID 4, 550 points) to 400 and 650, respectively. This is a very practical technique frequently used for things like campaigns targeting specific user segments.


【Interactive Playground】Experience Safe Data Updates by Running SQL in Your Browser!

Now, it's time to solidify this knowledge into a skill. Copy the entire HTML code below, save it as a file like sql_update_test.html, and open it in your browser. Your own personal SQL environment will launch, pre-loaded with the users table we've been using in this article.

First, practice updating data safely by making sure to use the WHERE clause. Try changing someone's points or updating an email address. The fastest way to improve is to run SELECT * FROM users; before and after the update to see with your own eyes how the results change.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>SQL UPDATE Statement Online Playground</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; line-height: 1.7; color: #333; max-width: 800px; margin: 2rem auto; padding: 0 1rem; }
    h1 { color: #2c3e50; }
    textarea { width: 100%; height: 180px; font-family: "SF Mono", "Consolas", monospace; font-size: 16px; padding: 12px; border: 1px solid #ccc; border-radius: 6px; box-sizing: border-box; margin-bottom: 1rem; }
    button { background-color: #f39c12; color: white; border: none; padding: 12px 22px; font-size: 16px; border-radius: 6px; cursor: pointer; transition: background-color 0.2s; }
    button:hover { background-color: #d35400; }
    button:disabled { background-color: #bdc3c7; cursor: not-allowed; }
    #result-container { margin-top: 2rem; border: 1px solid #ddd; padding: 1rem; border-radius: 6px; background: #fdfdfd; min-height: 50px; }
    #status-message { color: #27ae60; font-weight: bold; }
    #error-message { color: #e74c3c; font-weight: bold; }
    table { border-collapse: collapse; width: 100%; margin-top: 1rem; }
    th, td { border: 1px solid #ddd; padding: 10px; text-align: left; }
    th { background-color: #f2f2f2; }
    tr:nth-child(even) { background-color: #f9f9f9; }
  </style>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.10.3/sql-wasm.js"></script>
</head>
<body>

  <h1>Let's Try SQL!</h1>
  <p>Enter an UPDATE or SELECT statement in the textarea below and click the "Execute" button. Let's try updating the points for Ito with ID=5!</p>

  <textarea id="sql-input">-- Check the user data for ID=5 before the update
SELECT * FROM users WHERE id = 5;

-- Update the points for Ito with ID=5 to 200
UPDATE users
SET points = 200
WHERE id = 5;

-- Display all user data to confirm the update
SELECT * FROM users;
  </textarea>
  
  <button id="execute-btn">Execute</button>
  
  <div id="result-container">
    <p id="status-message"></p>
    <p id="error-message"></p>
    <div id="result-output"></div>
  </div>

  <script>
    const sqlInput = document.getElementById('sql-input');
    const executeBtn = document.getElementById('execute-btn');
    const statusMsg = document.getElementById('status-message');
    const errorMsg = document.getElementById('error-message');
    const resultOutput = document.getElementById('result-output');

    let db;

    async function initDb() {
      executeBtn.disabled = true;
      executeBtn.textContent = 'DB Initializing...';
      try {
        const SQL = await initSqlJs({
          locateFile: file => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.10.3/${file}`
        });
        db = new SQL.Database();
        
        const setupSql = `
          DROP TABLE IF EXISTS users;
          CREATE TABLE users (
            id INTEGER PRIMARY KEY,
            username TEXT NOT NULL,
            email TEXT NOT NULL,
            points INTEGER DEFAULT 0,
            last_login_date DATE
          );
          INSERT INTO users (id, username, email, points, last_login_date) VALUES
          (1, 'Yamada Taro', 'yamada@example.com', 50, '2025-06-15'),
          (2, 'Suzuki Hanako', 'suzuki@example.com', 120, '2025-06-20'),
          (3, 'Tanaka Jiro', 'tanaka@example.com', 300, '2025-06-28'),
          (4, 'Sato Misaki', 'sato@example.com', 550, '2025-06-30'),
          (5, 'Ito Kenta', 'ito@example.com', 80, '2025-05-30');
        `;
        db.run(setupSql);
        
        executeBtn.disabled = false;
        executeBtn.textContent = 'Execute';
        statusMsg.textContent = 'Ready! Try updating data with an UPDATE statement and check the results with a SELECT statement.';

      } catch (err) {
        errorMsg.textContent = 'Failed to initialize database: ' + err.message;
        console.error(err);
      }
    }

    function executeSql() {
      if (!db) return;
      
      const sql = sqlInput.value;
      statusMsg.textContent = '';
      errorMsg.textContent = '';
      resultOutput.innerHTML = '';

      try {
        const statements = sql.split(';').filter(s => s.trim() !== '');
        let lastResult;

        statements.forEach(stmt => {
          const trimmedStmt = stmt.trim();
          if (trimmedStmt.toUpperCase().startsWith('UPDATE') || trimmedStmt.toUpperCase().startsWith('INSERT') || trimmedStmt.toUpperCase().startsWith('DELETE')) {
            db.run(trimmedStmt);
            const changes = db.getRowsModified();
            statusMsg.innerHTML += `Query "${trimmedStmt.substring(0, 30)}..." executed, ${changes} row(s) modified.<br>`;
          } else {
             const results = db.exec(trimmedStmt);
             lastResult = results;
          }
        });

        if (lastResult && lastResult.length > 0) {
            lastResult.forEach(result => {
            const table = document.createElement('table');
            const thead = document.createElement('thead');
            const tbody = document.createElement('tbody');
            const headerRow = document.createElement('tr');
            result.columns.forEach(colName => {
                const th = document.createElement('th');
                th.textContent = colName;
                headerRow.appendChild(th);
            });
            thead.appendChild(headerRow);
            result.values.forEach(row => {
                const bodyRow = document.createElement('tr');
                row.forEach(cellValue => {
                const td = document.createElement('td');
                td.textContent = cellValue === null ? 'NULL' : cellValue;
                bodyRow.appendChild(td);
                });
                tbody.appendChild(bodyRow);
            });
            table.appendChild(thead);
            table.appendChild(tbody);
            resultOutput.appendChild(table);
            });
        }

      } catch (err) {
        errorMsg.textContent = 'SQL Error: ' + err.message;
        console.error(err);
      }
    }

    executeBtn.addEventListener('click', executeSql);
    
    initDb();
  </script>
</body>
</html>

Friends of UPDATE: CRUD Operations

By mastering UPDATE, you have acquired the third power of the basic data operations known as CRUD.

Now that you can "create," "read," and "update" data, all that's left is "delete" (DELETE). Once you learn that, you'll be able to perform all the basic database operations. You're almost at the finish line!


Conclusion

In this article, we've learned about the importance and usage of the UPDATE statement for safely updating existing data.

If INSERT is the "birth" of data, then UPDATE governs its "growth" and "change." It's an indispensable function for dynamic web applications, handling user information changes, status updates, and more. Always be mindful of the importance of the WHERE clause as your safety device, and get comfortable with data update operations. When used correctly, this power will dramatically expand the scope of applications you can build.