Databases 3 min read

How to Stream Large MySQL Query Results Without Running Out of Memory

MySQL normally loads an entire query result into memory, which can cause out‑of‑memory errors on large tables, but by adding the -q option in the console, enabling useCursorFetch in JDBC URLs, and setting stmt.setFetchSize(Integer.MIN_VALUE), you can switch to a streaming mode that returns rows one at a time.

ITPUB
ITPUB
ITPUB
How to Stream Large MySQL Query Results Without Running Out of Memory

By default MySQL retrieves the whole result set into memory before returning it, similar to Oracle's ALL_ROWS mode; this can cause memory overflow when the table is large.

To enable streaming results, you can:

When connecting via the MySQL console, add the -q option: mysql -h hostname -u root -p -q.

When using JDBC, add useCursorFetch=true to the connection URL.

In your Java code, create a forward‑only, read‑only statement and set the fetch size to Integer.MIN_VALUE:

stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
    java.sql.ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(Integer.MIN_VALUE);

The MySQL driver interprets Integer.MIN_VALUE as a signal to switch to streaming mode; it is not used as an actual fetch size value. With this setting, the driver retrieves rows one by one instead of loading the entire set into memory.

Refer to the MySQL documentation under “Resultset” for more details.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

performanceStreamingmysqlJDBCMemoryResultSet
ITPUB
Written by

ITPUB

Official ITPUB account sharing technical insights, community news, and exciting events.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.