HTML Web SQL UPDATE

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples + 3 Try It
UPDATE / WHERE / rowsAffected

Introduction

Web SQL lets web pages store data in a local SQLite database. Once rows exist, you use the SQL UPDATE statement to change existing values—user profiles, settings, cart quantities, and more. Although Web SQL is deprecated, learning updates helps you maintain legacy applications.

This tutorial focuses on updating records: writing UPDATE queries inside transactions, targeting rows with WHERE, checking rowsAffected, and handling errors safely.

What You’ll Learn

01

UPDATE

Change rows.

02

WHERE

Target rows.

03

SET cols

New values.

04

? bindings

Safe params.

05

rowsAffected

Verify change.

06

Transactions

Atomic writes.

What Is Web SQL?

Web SQL Database is a deprecated browser API for client-side relational storage. It uses SQLite under the hood, so standard SQL statements—including UPDATE—work the same way as in server databases.

The W3C deprecated Web SQL in favor of IndexedDB. Chrome removed it in version 97. Use this page to learn the API for education and legacy maintenance, not for new projects.

Why Update Records in Web SQL?

Data rarely stays static. Users edit profiles, change preferences, correct typos, or refresh cached values. The UPDATE statement modifies existing rows without deleting and re-inserting them.

  • User profiles — change name, email, or age fields.
  • App settings — toggle theme, language, or notification flags stored locally.
  • Sync status — mark rows as “sent to server” after background upload.
  • Inventory counts — adjust quantity when items are added or removed from a cart.
💡
Beginner Tip

UPDATE changes data in place. Use INSERT to add new rows and DELETE to remove them. Together they form full CRUD operations.

Creating the Database and Table Structure

Before updating, open the database and ensure the table exists. You can seed a row with INSERT so there is something to update.

js
const db = openDatabase('myDatabase', '1.0', 'Test DB', 2 * 1024 * 1024);

db.transaction(function (tx) {
  tx.executeSql(
    'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)'
  );
  tx.executeSql(
    'INSERT OR IGNORE INTO users (id, name, age) VALUES (?, ?, ?)',
    [1, 'John Doe', 25]
  );
});

INSERT OR IGNORE adds the starter row only if id 1 does not exist yet—handy for demos and first-run setup.

📝 UPDATE Syntax

Standard SQL syntax for modifying existing rows:

SQL
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;

In Web SQL, call it through executeSql with bound parameters:

js
tx.executeSql(
  'UPDATE users SET name = ?, age = ? WHERE id = ?',
  [newName, newAge, id],
  function (tx, result) { /* success */ },
  function (tx, error)  { /* failure */ }
);

Important rules

  • Always use WHERE when updating specific rows—omitting it updates every row in the table.
  • Bind values with ? — never concatenate user input into the SQL string.
  • Check result.rowsAffected — zero means no row matched (wrong id or missing record).
  • Run inside db.transaction — required by the Web SQL API.

⚡ Quick Reference

OperationCode pattern
Update one rowUPDATE t SET col = ? WHERE id = ?
Update multiple columnsSET name = ?, age = ? WHERE id = ?
Verify successresult.rowsAffected > 0
No matchrowsAffected === 0 — row not found
Update all rowsUPDATE t SET status = ? (no WHERE — use carefully)
Target
WHERE id = ?

One row

Set values
SET name = ?, age = ?

New data

Check
rowsAffected

Confirm hit

Safe
[val, id]

? bindings

Executing Update Queries

The UPDATE statement modifies columns on rows that match your WHERE condition. Wrap the logic in a reusable function:

js
function updateRecord(id, newName, newAge) {
  db.transaction(function (tx) {
    tx.executeSql(
      'UPDATE users SET name = ?, age = ? WHERE id = ?',
      [newName, newAge, id],
      function (tx, result) {
        console.log('Rows updated:', result.rowsAffected);
      },
      function (tx, error) {
        console.error('Update error:', error.message);
        return true;
      }
    );
  });
}

updateRecord(1, 'Jane Doe', 26);

This updates the name and age columns for the user with id = 1.

Handling Update Errors

Updates can fail silently when no row matches. Always inspect rowsAffected in the success callback and handle SQL errors in the error callback.

js
tx.executeSql(
  'UPDATE users SET name = ?, age = ? WHERE id = ?',
  [newName, newAge, id],
  function (tx, result) {
    if (result.rowsAffected === 0) {
      console.warn('No records were updated — check the id.');
    } else {
      console.log('Record updated successfully.');
    }
  },
  function (tx, error) {
    console.error('Update error:', error.message);
    return true;
  }
);
  • rowsAffected === 0 — the query ran but matched no rows (wrong id, or row was never inserted).
  • Error callback — syntax errors, constraint violations, or missing tables.
  • Return true from the error callback to roll back the transaction.

Examples Gallery

These examples use the Web SQL API pattern. Use the Try It Yourself links to run live demos. Web SQL works only in browsers that still expose openDatabase; otherwise the demo shows a clear status message.

📚 Getting Started

Update a single row by id with bound parameters.

Example 1 — Update a Single Row

Change name and age for user id 1.

js
const db = openDatabase('myDatabase', '1.0', 'Test DB', 2 * 1024 * 1024);

db.transaction(function (tx) {
  tx.executeSql('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)');
  tx.executeSql('INSERT OR IGNORE INTO users (id, name, age) VALUES (?, ?, ?)', [1, 'John Doe', 25]);

  tx.executeSql(
    'UPDATE users SET name = ?, age = ? WHERE id = ?',
    ['Jane Doe', 26, 1],
    function (tx, result) {
      console.log('Updated rows:', result.rowsAffected);
    },
    function (tx, error) {
      console.error('Error:', error.message);
    }
  );
});
Try It Yourself

How It Works

The transaction creates the table, seeds John Doe, then updates that row to Jane Doe age 26. rowsAffected returns 1 when exactly one row changed.

Example 2 — Reusable updateRecord Function

Call the same function from buttons, forms, or sync handlers.

js
function updateRecord(id, newName, newAge) {
  db.transaction(function (tx) {
    tx.executeSql(
      'UPDATE users SET name = ?, age = ? WHERE id = ?',
      [newName, newAge, id],
      function (tx, result) {
        console.log('Updated', result.rowsAffected, 'row(s)');
      },
      function (tx, error) {
        console.error('Update error:', error.message);
        return true;
      }
    );
  });
}

updateRecord(1, 'Jane Doe', 26);
updateRecord(2, 'Alex Kim', 30);
Try It Yourself

How It Works

The second call returns 0 rows if id 2 was never inserted—a signal to insert first or show “user not found.”

📈 Practical Patterns

Verify updates, bind form values, and build a complete demo page.

Example 3 — Detect When No Row Matches

Use rowsAffected to warn when the target id does not exist.

js
function updateUser(id, name) {
  db.transaction(function (tx) {
    tx.executeSql(
      'UPDATE users SET name = ? WHERE id = ?',
      [name, id],
      function (tx, result) {
        if (result.rowsAffected === 0) {
          console.warn('No user with id', id);
        } else {
          console.log('Name updated for id', id);
        }
      }
    );
  });
}

updateUser(99, 'Ghost User'); /* id 99 does not exist */
Try It Yourself

How It Works

Unlike a SQL error, updating a missing id succeeds with rowsAffected === 0. Your app should treat that as “not found” rather than success.

Example 4 — Update from Form Input

Read values from input fields and bind them to the UPDATE query.

js
document.getElementById('saveBtn').addEventListener('click', function () {
  const name = document.getElementById('nameInput').value.trim();
  const age  = parseInt(document.getElementById('ageInput').value, 10);

  if (!name || isNaN(age)) return;

  db.transaction(function (tx) {
    tx.executeSql(
      'UPDATE users SET name = ?, age = ? WHERE id = ?',
      [name, age, 1],
      function (tx, result) {
        alert(result.rowsAffected ? 'Saved!' : 'User not found.');
      }
    );
  });
});
Try It Yourself

How It Works

Validate input in JavaScript first, then pass clean values through ? bindings. Never build SQL like "UPDATE ... SET name = '" + name + "'".

Example 5 — Complete HTML Page (Add + Update)

Insert a record, then update it with a second button—matching the classic Web SQL workflow.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Web SQL Update Example</title>
</head>
<body>
  <h1>Web SQL Update Example</h1>
  <button type="button" id="addRecord">Add Record</button>
  <button type="button" id="updateRecord">Update Record</button>
  <p id="status"></p>

  <script>
    if (!window.openDatabase) {
      document.getElementById('status').textContent =
        'Web SQL is not supported in this browser.';
    } else {
      const db = openDatabase('myDatabase', '1.0', 'Test DB', 2 * 1024 * 1024);

      db.transaction(function (tx) {
        tx.executeSql(
          'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)'
        );
      });

      document.getElementById('addRecord').addEventListener('click', function () {
        db.transaction(function (tx) {
          tx.executeSql(
            'INSERT OR REPLACE INTO users (id, name, age) VALUES (?, ?, ?)',
            [1, 'John Doe', 25],
            function () {
              document.getElementById('status').textContent = 'Added John Doe';
            }
          );
        });
      });

      document.getElementById('updateRecord').addEventListener('click', function () {
        updateRecord(1, 'Jane Doe', 26);
      });

      function updateRecord(id, newName, newAge) {
        db.transaction(function (tx) {
          tx.executeSql(
            'UPDATE users SET name = ?, age = ? WHERE id = ?',
            [newName, newAge, id],
            function (tx, result) {
              document.getElementById('status').textContent =
                result.rowsAffected
                  ? 'Updated to ' + newName
                  : 'No row found — add a record first';
            },
            function (tx, error) {
              document.getElementById('status').textContent = 'Error: ' + error.message;
              return true;
            }
          );
        });
      }
    }
  </script>
</body>
</html>
Try It Yourself

How It Works

Click Add Record to seed id 1, then Update Record changes name and age. Status text on the page gives immediate feedback.

🚀 Common Use Cases

  • Profile editing — update display name, bio, or avatar URL fields.
  • Settings panels — persist theme, font size, or language preferences.
  • Offline sync flags — set synced = 1 after uploading to a server.
  • Cart quantities — change qty when users add or remove items.
  • Legacy app maintenance — patch existing Web SQL data in older mobile web apps.

🧠 How Web SQL UPDATE Works

1

Find rows

WHERE id = ? selects matching rows.

Filter
2

Set new values

SET name = ?, age = ? assigns columns.

Modify
3

Commit transaction

Changes persist when the transaction succeeds.

Save
=

Row updated

rowsAffected tells you how many rows changed.

📝 Notes

  • Web SQL is deprecated—use IndexedDB for new apps.
  • Always include WHERE unless you intentionally update every row.
  • Check rowsAffected—zero means no match, not necessarily an error.
  • Bind all dynamic values with ? placeholders.
  • UPDATE cannot create new rows—use INSERT first.
  • Combine with SELECT to read back the updated values.

Browser Support

Web SQL was never implemented in Firefox. Chrome removed it in Chrome 97. Safari historically supported it on some versions. Feature-detect with window.openDatabase before running demos.

Baseline · Since HTML

Web SQL API

Web SQL was never implemented in Firefox. Chrome removed it in Chrome 97. Safari historically supported it on some versions. Feature-detect with window.openDatabase before running demos.

25% Modern browser support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
Web SQL API Deprecated

Bottom line: For cross-browser storage today, use IndexedDB.

💡 Best Practices

✅ Do

  • Use WHERE to target specific rows
  • Bind values with ? placeholders
  • Check result.rowsAffected after every update
  • Validate form input before writing to the database
  • Handle error callbacks and return true to roll back
  • Prefer IndexedDB for new projects

❌ Don’t

  • Omit WHERE unless you mean to update all rows
  • Concatenate user input into SQL strings
  • Assume success when rowsAffected is 0
  • Use UPDATE to create rows that do not exist
  • Skip transactions around your executeSql calls
  • Build new features on Web SQL in 2026

Conclusion

Updating records with Web SQL means running UPDATE ... SET ... WHERE ... inside db.transaction, binding values safely, and checking rowsAffected to confirm the right row changed.

You have now covered the full Web SQL CRUD series—DELETE, INSERT, SELECT, and UPDATE. For modern apps, carry these SQL concepts forward with IndexedDB or a server-side database.

Key Takeaways

Knowledge Unlocked

Five things to remember about Web SQL UPDATE

Use these points when modifying rows in a client-side database.

5
Core concepts
🎯 02

WHERE

Target id.

Filter
🔒 03

? bindings

Safe params.

Security
🔢 04

rowsAffected

Verify hit.

Reliability
🔄 05

Deprecated

Use IndexedDB.

Modern

❓ Frequently Asked Questions

Open the database with openDatabase(), then call db.transaction(). Inside the transaction, use tx.executeSql() with an UPDATE statement and a WHERE clause. Bind new values and the target id with ? placeholders: UPDATE users SET name = ?, age = ? WHERE id = ?
Standard SQL: UPDATE table_name SET column1 = ?, column2 = ? WHERE condition. Always include a WHERE clause when updating specific rows—without it, every row in the table is updated.
Check result.rowsAffected in the success callback. If it is 0, no row matched your WHERE clause (wrong id, or the row does not exist yet).
Web SQL requires all executeSql calls inside db.transaction(). Transactions keep changes atomic—if a later statement fails, earlier changes in the same transaction can roll back.
Web SQL is deprecated and removed from most modern browsers (including current Chrome). Treat this tutorial as educational for legacy code; use IndexedDB for new projects.
UPDATE changes columns on existing rows matched by WHERE. INSERT OR REPLACE inserts a new row or replaces the entire row when the primary key exists. Use UPDATE when you only want to change specific fields.
Did you know?

An UPDATE with no WHERE clause changes every row in the table. That is occasionally useful for bulk flags (e.g. mark all items as read), but it is a common source of bugs when you meant to change just one record.

Practice Web SQL UPDATE

Add a user, click update, and watch the status message change in the Try It editor.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful