Skip to content

[jdbc-v2] Improve sending big SQL #3523

In progress
In progress

Description

@chernser

Description

Analytical SQL's and insert statements can be huge. When PreparedStatement is used this also complicated by composing SQL on client with all parameters. Heavy load happens when application need to insert big batch of information and uses, for example, convert function that makes impossible to use RowBinary format.

In this case we need to make certain optimizations.

Activity

  1. added this to the 0.12.0 milestone on Dec 4, 2026
  2. added theissue type on Dec 4, 2026
  3. added
    jdbc
    queries
    on Dec 4, 2026
  4. polyglotAI-bot commented on Dec 4, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Keep open — review PR #3524
    Draft PR #3524 closes this issue. With its diff, a 200,000-row batch with a function in VALUES allocates 18 MB in place of 305 MB, in about 90 ms in place of 210 ms. It covers only single-group INSERT … VALUES: a SELECT with ? still builds the full SQL string.

    • Category: Performance
    • Classification: impact: Performance · area: Queries (large statements)
    • Status on main: Reproduced on main — one batch makes 17.7 MB of SQL text, and the calling thread allocates about 305 MB (17×) for it.
    • Breaking change: No — can be done without a break, if the SQL that the server gets stays the same.
    • Duplicates / related: Same root cause as [performance][jdbc] Insert operation when RowBinary not available #3332 — its item "streamline writing big SQL statements" is this request; our comment there gives the allocations of each step.

    Analysis: main keeps the full SQL text in memory several times: addBatch copies each VALUES tuple into a StringBuilder (PreparedStatementImpl.java:323-330), executeBatch joins all tuples into one more StringBuilder and String (PreparedStatementImpl.java:369-377), JDBC escape processing copies it again (StatementImpl.java:101, called at :407), and the HTTP layer copies it to a byte[] (HttpAPIClientHelper.java:663). Client.query takes only a String, so jdbc-v2 cannot stream a statement on main.

    Reproduction: complete program and output

    Allocations of the calling thread (ThreadMXBean); the table has the Null engine, so the server stores nothing.

    import java.lang.management.ManagementFactory;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.Statement;
    import java.util.Properties;
    
    public class Repro {
        static final String URL = System.getenv().getOrDefault("CLICKHOUSE_URL", "http://localhost:8123");
        static final String PASSWORD = System.getenv().getOrDefault("CLICKHOUSE_PASSWORD", "");
        static final int ROWS = 200_000;
        static final String S = "some text value of about forty characters";
        static final String TS = "2026-12-04 10:00:00";
    
        static final com.sun.management.ThreadMXBean MX =
                (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
    
        public static void main(String[] args) throws Exception {
            Properties props = new Properties();
            props.setProperty("user", "default");
            props.setProperty("password", PASSWORD);
            String jdbcUrl = "jdbc:clickhouse:" + URL.replaceFirst("^https?:", "") + "/default";
            try (Connection conn = DriverManager.getConnection(jdbcUrl, props)) {
                try (Statement st = conn.createStatement()) {
                    st.execute("DROP TABLE IF EXISTS triage_3523");
                    st.execute("CREATE TABLE triage_3523 (id UInt64, s String, ts DateTime) ENGINE = Null");
                }
                // The SQL size of one batch: each row is the VALUES template with the literals in it.
                long sqlChars = "INSERT INTO triage_3523 VALUES ".length();
                for (int i = 0; i < ROWS; i++) {
                    sqlChars += ("(" + i + ", '" + S + "', toDateTime('" + TS + "'))").length() + 1;
                }
                System.out.printf("rows per batch: %d, SQL size: %.1f MB%n", ROWS, sqlChars / 1e6);
                // A function in VALUES, so the RowBinary writer cannot be used.
                String sql = "INSERT INTO triage_3523 VALUES (?, ?, toDateTime(?))";
                try (PreparedStatement ps = conn.prepareStatement(sql)) {
                    System.out.println("PreparedStatement class: " + ps.getClass().getSimpleName());
                    for (int run = 0; run < 4; run++) {
                        long tid = Thread.currentThread().getId();
                        long a0 = MX.getThreadAllocatedBytes(tid);
                        long t0 = System.nanoTime();
                        for (int i = 0; i < ROWS; i++) {
                            ps.setLong(1, i);
                            ps.setString(2, S);
                            ps.setString(3, TS);
                            ps.addBatch();
                        }
                        int[] res = ps.executeBatch();
                        long ms = (System.nanoTime() - t0) / 1_000_000;
                        long mb = (MX.getThreadAllocatedBytes(tid) - a0) / 1_000_000;
                        System.out.printf("%s: %d rows, %d ms, %d MB allocated (%.1fx the SQL size)%n",
                                run == 0 ? "warm-up" : "batch " + run, res.length, ms, mb, mb * 1e6 / sqlChars);
                    }
                }
                try (Statement st = conn.createStatement()) {
                    st.execute("DROP TABLE triage_3523");
                }
            }
        }
    }

    Output on main (f16f8e1a2), ClickHouse 26.11.7.10:

    rows per batch: 200000, SQL size: 17.7 MB
    PreparedStatement class: PreparedStatementImpl
    warm-up: 200000 rows, 275 ms, 310 MB allocated (17.5x the SQL size)
    batch 1: 200000 rows, 205 ms, 305 MB allocated (17.2x the SQL size)
    batch 2: 200000 rows, 212 ms, 305 MB allocated (17.2x the SQL size)
    batch 3: 200000 rows, 268 ms, 305 MB allocated (17.2x the SQL size)
    

    Output with the diff of PR #3524 (246ecece5) applied on main:

    rows per batch: 200000, SQL size: 17.7 MB
    PreparedStatement class: StreamingPreparedStatementImpl
    warm-up: 200000 rows, 114 ms, 18 MB allocated (1.0x the SQL size)
    batch 1: 200000 rows, 99 ms, 18 MB allocated (1.0x the SQL size)
    batch 2: 200000 rows, 88 ms, 18 MB allocated (1.0x the SQL size)
    batch 3: 200000 rows, 84 ms, 18 MB allocated (1.0x the SQL size)
    

    Automated triage by Polyglot AI. A maintainer makes the final decision.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jdbcperformancequeries

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions