On this page
This page has instructions for updating rows of data (using the UPDATE statement) in CockroachDB from various programming languages.
Before you begin
Make sure you have already:
- Set up a local cluster.
- Installed a Postgres client.
- Connected to the database.
- Inserted data that you now want to update.
Note:
Your application should use a retry loop to handle transaction errors that can occur under contention.
Update a row
UPDATE accounts SET balance = 900 WHERE id = 1; For more information about how to use the built-in SQL client, see the cockroach sql reference docs.
// tx is a *sql.Tx from "database/sql" transferAmount := 100 fromID := 1 if _, err := tx.Exec("UPDATE accounts SET balance = balance - $1 WHERE id = $2", transferAmount, fromID); err != nil { return err } For complete examples, see:
// ds is an org.postgresql.ds.PGSimpleDataSource int transferAmount = 100; int fromID = 1; try (Connection connection = ds.getConnection()) { connection.createStatement().executeUpdate("UPDATE accounts SET balance = balance - " + transferAmount + " where id = " + fromID); } catch (SQLException e) { System.out.printf("sql state = [%s]\ncause = [%s]\nmessage = [%s]\n", e.getSQLState(), e.getCause(), e.getMessage()); } For complete examples, see:
# conn is a psycopg2 connection transferAmount = 100 fromID = 1 with conn.cursor() as cur: cur.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s", (transferAmount, fromID)); conn.commit() For complete examples, see:
See also
Reference information related to this task:
Other common tasks: