> ## Documentation Index
> Fetch the complete documentation index at: https://www.cockroachlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Insert Data

export const InternalLink = ({version, path = "", children, ...props}) => {
  let detectedVersion = version || "stable";
  if (typeof window !== 'undefined' && !version) {
    const match = window.location.pathname.match(/\/docs\/([^/]+)/);
    if (match) {
      detectedVersion = match[1];
    }
  }
  const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
  return <a href={`/docs/${detectedVersion}/${normalizedPath}`} {...props}>
      {children}
    </a>;
};

This page has instructions for getting data into CockroachDB with various programming languages, using the <InternalLink path="insert">`INSERT`</InternalLink> SQL statement.

## Before you begin

Before reading this page, do the following:

* <InternalLink version="cockroachcloud" path="quickstart">Create a CockroachDB Standard cluster</InternalLink> or <InternalLink version="cockroachcloud" path="quickstart?filters=local">start a local cluster</InternalLink>.
* <InternalLink path="install-client-drivers">Install a Driver or ORM Framework</InternalLink>.
* <InternalLink path="connect-to-the-database">Connect to the database</InternalLink>.

<Note>
  When running under the default <InternalLink path="demo-serializable">`SERIALIZABLE`</InternalLink> isolation level, your application should <InternalLink path="query-behavior-troubleshooting#transaction-retry-errors">use a retry loop to handle transaction retry errors</InternalLink> that can occur under <InternalLink path="performance-best-practices-overview#understanding-and-avoiding-transaction-contention">contention</InternalLink>.
</Note>

## Insert rows

When inserting multiple rows, a single <InternalLink path="insert#insert-multiple-rows-into-an-existing-table">multi-row insert statement</InternalLink> is faster than multiple single-row statements.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT);
INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250);
```

For more information about how to use the built-in SQL client, see the <InternalLink path="cockroach-sql">`cockroach sql`</InternalLink> reference docs.

```go theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
// 'db' is an open database connection

// Insert two rows into the "accounts" table.
if _, err := db.Exec(
    "INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)"); err != nil {
    log.Fatal(err)
}
```

For complete examples, see:

* <InternalLink path="build-a-go-app-with-cockroachdb">Build a Go App with CockroachDB</InternalLink> (pgx)
* <InternalLink path="build-a-go-app-with-cockroachdb">Build a Go App with CockroachDB and GORM</InternalLink>

```java theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
// ds is an org.postgresql.ds.PGSimpleDataSource

try (Connection connection = ds.getConnection()) {
    connection.setAutoCommit(false);
    PreparedStatement pstmt = connection.prepareStatement("INSERT INTO accounts (id, balance) VALUES (?, ?)");

    pstmt.setInt(1, 1);
    pstmt.setInt(2, 1000);
    pstmt.addBatch();

    pstmt.executeBatch();
    connection.commit();
} catch (SQLException e) {
    System.out.printf("sql state = [%s]\ncause = [%s]\nmessage = [%s]\n",
                      e.getSQLState(), e.getCause(), e.getMessage());
}
```

For complete examples, see:

* <InternalLink path="build-a-java-app-with-cockroachdb">Build a Java App with CockroachDB</InternalLink> (JDBC)
* <InternalLink path="build-a-java-app-with-cockroachdb-hibernate">Build a Java App with CockroachDB and Hibernate</InternalLink>

```python theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
# conn is a psycopg2 connection

with conn.cursor() as cur:
    cur.execute('INSERT INTO accounts (id, balance) VALUES (1, 1000), (2, 250)')

conn.commit()
```

For complete examples, see:

* <InternalLink path="build-a-python-app-with-cockroachdb-psycopg3">Build a Python App with CockroachDB</InternalLink> (psycopg3)
* <InternalLink path="build-a-python-app-with-cockroachdb-sqlalchemy">Build a Python App with CockroachDB and SQLAlchemy</InternalLink>
* <InternalLink path="build-a-python-app-with-cockroachdb-django">Build a Python App with CockroachDB and Django</InternalLink>
* <InternalLink path="build-a-python-app-with-cockroachdb-asyncpg">Build a Python App with CockroachDB and asyncpg</InternalLink>

## Limit the size of rows

To help you avoid failures arising from misbehaving applications that bloat the size of rows, you can specify the behavior when a row or individual <InternalLink path="column-families">column family</InternalLink> larger than a specified size is written to the database. Use the <InternalLink path="cluster-settings">cluster settings</InternalLink> `sql.guardrails.max_row_size_log` to discover large rows and `sql.guardrails.max_row_size_err` to reject large rows.

When you write a row that exceeds `sql.guardrails.max_row_size_log`:

* `INSERT`, `UPSERT`, `UPDATE`, `CREATE TABLE AS`, `CREATE INDEX`, `ALTER TABLE`, `ALTER INDEX`, `IMPORT`, or `RESTORE` statements will log a `LargeRow` to the <InternalLink path="logging#sql_perf">`SQL_PERF`</InternalLink> channel.
* `SELECT`, `DELETE`, `TRUNCATE`, and `DROP` are not affected.

When you write a row that exceeds `sql.guardrails.max_row_size_err`:

* `INSERT`, `UPSERT`, and `UPDATE` statements will fail with a code `54000 (program_limit_exceeded)` error.
* `CREATE TABLE AS`, `CREATE INDEX`, `ALTER TABLE`, `ALTER INDEX`, `IMPORT`, and `RESTORE` statements will log a `LargeRowInternal` event to the <InternalLink path="logging#sql_internal_perf">`SQL_INTERNAL_PERF`</InternalLink> channel.
* `SELECT`, `DELETE`, `TRUNCATE`, and `DROP` are not affected.

You **cannot** update existing rows that violate the limit unless the update shrinks the size of the row below the limit. You **can** select, delete, alter, back up, and restore such rows. We recommend using the accompanying setting `sql.guardrails.max_row_size_log` in conjunction with `SELECT pg_column_size()` queries to detect and fix any existing large rows before lowering `sql.guardrails.max_row_size_err`.

## See also

Reference information related to this task:

* <InternalLink version="molt" path="migration-overview">Migration Overview</InternalLink>
* <InternalLink path="insert">`INSERT`</InternalLink>
* <InternalLink path="upsert">`UPSERT`</InternalLink>
* <InternalLink path="performance-best-practices-overview#transaction-contention">Transaction Contention</InternalLink>
* <InternalLink path="performance-best-practices-overview#dml-best-practices">Multi-row DML best practices</InternalLink>
* <InternalLink path="insert#insert-multiple-rows-into-an-existing-table">Insert Multiple Rows</InternalLink>

Other common tasks:

* <InternalLink path="connect-to-the-database">Connect to the Database</InternalLink>
* <InternalLink path="query-data">Query Data</InternalLink>
* <InternalLink path="update-data">Update Data</InternalLink>
* <InternalLink path="delete-data">Delete Data</InternalLink>
* <InternalLink path="run-multi-statement-transactions">Run Multi-Statement Transactions</InternalLink>
* <InternalLink path="query-behavior-troubleshooting">Troubleshoot SQL Statements</InternalLink>
* <InternalLink path="make-queries-fast">Optimize Statement Performance</InternalLink>
* <InternalLink path="example-apps">Example Apps</InternalLink>
