问题
When executing a SQL query on a Postgres database using the psql client, it nicely formats the results and displays them in a pager (by default). How to change this behavior to make psql display results as soon as they are available rather than waiting for the full result set to computed (in a larger computation)? Of course, aligned output cannot be expected in this case, because the width of the individual columns is not known before they are to be printed.
回答1:
Not processing the full result set before displaying means two different things in psql:
1) Aligned mode. To compute the maximum width of any column to display aligned results, all the rows must be fetched in the client. When not desirable, this should turned off with the \a command:
\a toggle between unaligned and aligned output mode
2) FETCH_COUNT. This parameter when set (e.g. \set FETCH_COUNT 10000) indicates that the client should request the results from the server by chunks as opposed to a big single resultset. Internally it uses a cursor. Documented as:
FETCH_COUNT
If this variable is set to an integer value > 0, the results of
SELECT queries are fetched and displayed in groups of that many
rows, rather than the default behavior of collecting the entire
result set before display. Therefore only a limited amount of
memory is used, regardless of the size of the result set.
Settings of 100 to 1000 are commonly used when enabling this
feature. Keep in mind that when using this feature, a query
might fail after having already displayed some rows.
Combining FETCH_COUNT and unaligned mode will get the results to screen or file as fast as possible.
Besides, fetching in chunks and aligned mode don't play well together, as we're warned about (still from psql's manpage):
Tip Although you can use any output format with this feature, the default aligned format tends to look bad because each group of FETCH_COUNT rows will be formatted separately, leading to varying column widths across the row groups. The other output formats work better.
回答2:
That is unfortunately not possible in the standard psql client.
You can in most cases use LIMIT and OFFSET to limit the amount of data that needs to be fetched, also see CURSOR http://www.postgresql.org/docs/9.3/static/plpgsql-cursors.html You can't use CURSOR in psql, sorry.
It is possible to create a client that works in the way you want, here is some info: http://www.postgresql.org/docs/9.3/static/libpq-single-row-mode.html
Update: The above is incorrect. you can do it by using ex. \set FETCH_COUNT 10
See Daniels answer
来源:https://stackoverflow.com/questions/22424625/how-to-view-results-as-soon-as-they-arrive-in-psql