Sub topic 3
Printing results with DBMS_OUTPUT
This chapter assumes you can run a PL/SQL anonymous block in SQL*Plus, SQL Developer, or SQLcl, and that you know the block layout of DECLARE, BEGIN, EXCEPTION, and END. You will learn how DBMS_OUTPUT works, why output sometimes does not appear, and which limits to watch for.
What DBMS_OUTPUT is
PL/SQL has no built-in print statement. The language runs inside the database server, and the server has no screen to write to. DBMS_OUTPUT is a supplied package that works around this in two steps:
- Your block calls a procedure such as
DBMS_OUTPUT.PUT_LINE. The text goes into a buffer in the session's server memory. - After the call finishes, the client tool asks the server for the buffered lines and shows them.
The client must do step 2. In SQL*Plus and SQLcl you turn it on with SET SERVEROUTPUT ON. SQL Developer has a DBMS Output panel, where you click the plus icon to enable output for a connection.
SET SERVEROUTPUT ON
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello from the buffer');
END;
/If you leave out SET SERVEROUTPUT ON, the block still succeeds. The text is written to the buffer and never fetched, so you see only PL/SQL procedure successfully completed.. This is the most common reason people think PUT_LINE is broken.
The procedures in the package
The package has a small set of subprograms.
| Subprogram | Purpose |
|---|---|
| `PUT_LINE(item)` | Writes the item and a line terminator to the buffer. |
| `PUT(item)` | Writes the item with no line terminator. |
| `NEW_LINE` | Writes a line terminator, which ends the current line. |
| `ENABLE(buffer_size)` | Turns buffering on and sets the buffer size. |
| `DISABLE` | Turns buffering off and discards the buffer contents. |
| `GET_LINE(line, status)` | Reads one line back from the buffer. |
| `GET_LINES(lines, numlines)` | Reads several lines back from the buffer. |
In everyday work you use PUT_LINE almost exclusively. The client tool calls GET_LINE or GET_LINES for you when SERVEROUTPUT is on.
Printing with PUT_LINE
PUT_LINE accepts one argument. It has overloads for VARCHAR2, NUMBER, and DATE, so you can pass a number directly. Everything is converted to text.
SET SERVEROUTPUT ON
DECLARE
v_count NUMBER := 42;
BEGIN
DBMS_OUTPUT.PUT_LINE(v_count);
DBMS_OUTPUT.PUT_LINE('Count is ' || v_count);
END;
/Because there is only one argument, you cannot write PUT_LINE('Count is ', v_count). That call fails to compile. Build one string with the concatenation operator || instead.
Conversion and NULL behavior
Two conversion rules cause most surprises.
- When you concatenate a number or date, Oracle converts it implicitly. Dates use the session's
NLS_DATE_FORMAT, so the same code can print differently for different sessions. CallTO_CHARwith an explicit format when the appearance matters. - Concatenating
NULLwith a string gives the string. It does not giveNULL. ANULLvariable therefore prints as nothing, and the output is easy to misread.
SET SERVEROUTPUT ON
DECLARE
v_bonus NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('Bonus: ' || v_bonus);
DBMS_OUTPUT.PUT_LINE('Today: ' || TO_CHAR(SYSDATE, 'YYYY-MM-DD'));
DBMS_OUTPUT.PUT_LINE('Bonus (safe): ' || NVL(TO_CHAR(v_bonus), '<null>'));
END;
/The first line prints Bonus: with nothing after it. The third line makes the missing value visible. When you debug, printing a marker such as <null> saves time.
Printing a BOOLEAN
No overload accepts a BOOLEAN, and || does not convert one. Use a CASE expression to turn the value into text.
SET SERVEROUTPUT ON
DECLARE
v_active BOOLEAN := TRUE;
BEGIN
DBMS_OUTPUT.PUT_LINE(
'Active: ' || CASE WHEN v_active THEN 'TRUE'
WHEN NOT v_active THEN 'FALSE'
ELSE 'NULL' END);
END;
/A BOOLEAN can also be NULL, which is why the expression needs a third branch.
Building a line in pieces with PUT and NEW_LINE
PUT adds text to the current line without ending it. NEW_LINE ends the line. This is useful when a loop produces one column at a time.
SET SERVEROUTPUT ON
BEGIN
FOR i IN 1 .. 5 LOOP
DBMS_OUTPUT.PUT(i);
IF i < 5 THEN
DBMS_OUTPUT.PUT(', ');
END IF;
END LOOP;
DBMS_OUTPUT.NEW_LINE;
END;
/This prints 1, 2, 3, 4, 5 on a single line.
The NEW_LINE call is required. If a block ends while a partial line is still pending, that partial text is never delivered, so the output vanishes with no error. If a block that uses PUT prints nothing, check for a missing NEW_LINE.
When the output appears
The client fetches the buffer only after the whole block has returned. Calls to PUT_LINE inside a long loop do not appear one by one as the loop runs. All the lines arrive together at the end.
The sequence looks like this:
Three consequences follow from this design.
- You cannot use
DBMS_OUTPUTto watch the progress of a long job. For that, useDBMS_APPLICATION_INFO.SET_SESSION_LONGOPSor write to a log table. - If the block raises an unhandled exception, the lines written before the error are still delivered. You see them above the error message.
- If the session ends or the block is never fetched, for example when called from application code that does not read the buffer, the text is lost.
Buffer size and line length
The buffer lives in server memory, so it has limits.
- Total size. In Oracle Database 10g Release 2 and later,
SET SERVEROUTPUT ONuses an unlimited buffer by default. In older releases the default was 2,000 bytes with a 1,000,000-byte maximum, and the overflow error isORU-10027: buffer overflow. You can set the size withSET SERVEROUTPUT ON SIZE 1000000, or in code withDBMS_OUTPUT.ENABLE(1000000). - Line length. A single line can hold at most 32,767 bytes. A longer line raises
ORA-06502. In releases before 10g Release 2 the limit was 255 bytes. - Memory. An unlimited buffer lets a runaway loop use a lot of memory in the server process. Do not print millions of rows to the buffer.
SET SERVEROUTPUT ON SIZE UNLIMITED
BEGIN
DBMS_OUTPUT.ENABLE(NULL); -- NULL means unlimited in 10gR2 and later
DBMS_OUTPUT.PUT_LINE('Buffer enabled with no size cap');
END;
/The SIZE option in the client command and the ENABLE call in code are separate. The client command calls ENABLE on your behalf, so a later call in your block replaces that setting.
Formatting options in SQL*Plus and SQLcl
SQL*Plus removes leading blanks from output lines by default. If you indent text to show structure, add the FORMAT option:
SET SERVEROUTPUT ON FORMAT WRAPPED
BEGIN
DBMS_OUTPUT.PUT_LINE('Employees');
DBMS_OUTPUT.PUT_LINE(' King');
DBMS_OUTPUT.PUT_LINE(' Kochhar');
END;
/With WRAPPED, the indentation is kept and long lines wrap at the line size. Other options are WORD_WRAPPED and TRUNCATED. SHOW SERVEROUTPUT displays the current settings.
Using DBMS_OUTPUT with variables from this tutorial
You have seen PUT_LINE in earlier examples of the declaration and executable sections. Here is a case that combines it with %TYPE, SELECT INTO, and a safe way to print possibly-null columns:
SET SERVEROUTPUT ON
DECLARE
v_last_name employees.last_name%TYPE;
v_commission employees.commission_pct%TYPE;
BEGIN
SELECT last_name, commission_pct
INTO v_last_name, v_commission
FROM employees
WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE('Name: ' || v_last_name);
DBMS_OUTPUT.PUT_LINE('Commission: ' || NVL(TO_CHAR(v_commission), 'none'));
END;
/The employee with ID 100 has no commission in the standard HR sample data, so the second line prints none. Without NVL, the line would end after Commission: .
Common mistakes
| Symptom | Likely cause | Fix | Column | Column |
|---|---|---|---|---|
| Block succeeds and prints nothing | `SERVEROUTPUT` is off | Run `SET SERVEROUTPUT ON`. | ||
| `PLS-00306` on a `PUT_LINE` call | Two arguments were passed | Combine them with `\ | \ | `. |
| Text from `PUT` never appears | No `NEW_LINE` before the block ended | Call `NEW_LINE`. | ||
| Output is not indented | SQL*Plus trims leading blanks | Use `FORMAT WRAPPED`. | ||
| `ORU-10027` | Fixed buffer is full | Use `SIZE UNLIMITED` or a larger size. | ||
| `ORA-06502` on print | One line is longer than 32,767 bytes | Split the text into several calls. | ||
| Value prints as blank | The variable is `NULL` | Use `NVL` or a `CASE` expression. |
When not to use DBMS_OUTPUT
DBMS_OUTPUT is a development and debugging tool. It does not suit these jobs:
- Production logging. Nothing is persisted, and nobody reads the buffer from a scheduled job. Write to a log table, ideally from an autonomous transaction so the log survives a rollback.
- Returning data to an application. Use
OUTparameters, a function return value, or aREF CURSOR. - Progress monitoring. The buffer is not readable until the block ends.
Summary of the working model
DBMS_OUTPUTwrites to a server-side buffer, and the client displays it after the block returns.SET SERVEROUTPUT ONis a client setting, not part of your PL/SQL code.PUT_LINEtakes one argument. Build the string with||, convert withTO_CHAR, and guard againstNULL.PUTneeds a closingNEW_LINE.- Limits are 32,767 bytes per line and, depending on version and settings, a bounded or unbounded buffer.
Exercise
A block loops 1,000 times and calls DBMS_OUTPUT.PUT(i) each time to build one line of numbers. It runs without errors, but SQL*Plus shows nothing, even though SET SERVEROUTPUT ON was run. Give the most likely cause and the fix.
Show answer
The block never calls DBMSOUTPUT.NEWLINE. PUT only appends to the current line, and a partial line still pending when the block ends is not delivered to the client. Add DBMSOUTPUT.NEWLINE after the loop, or use PUT_LINE for the last item. Also check that the combined line stays under 32,767 bytes, because a line this long can raise ORA-06502 once the limit is exceeded.
Exercise
Write a block that declares vhire employees.hiredate%TYPE, selects the hire date of employee 100 into it, and prints it as 'Hired: ' followed by the date in the format DD-MON-YYYY, so the output does not depend on the session's NLSDATEFORMAT.
Show answer
DECLARE vhire employees.hiredate%TYPE; BEGIN SELECT hiredate INTO vhire FROM employees WHERE employeeid = 100; DBMSOUTPUT.PUTLINE('Hired: ' || TOCHAR(vhire, 'DD-MON-YYYY')); END; / Run SET SERVEROUTPUT ON first. The explicit TOCHAR format mask replaces the implicit conversion that uses NLSDATEFORMAT.